import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, NotFoundError } from '@/lib/errors';
import {
  deleteReportSchedule,
  getReportSchedule,
  updateReportSchedule,
} from '@/lib/services/report-schedules.service';
import { updateReportScheduleSchema } from '@/lib/validators/reports';

/**
 * GET    /api/v1/reports/schedules/[id]
 * PATCH  /api/v1/reports/schedules/[id]   — update cadence, recipients,
 *                                            output, or enabled state.
 *                                            Re-enable triggers a fresh
 *                                            nextRunAt computation.
 * DELETE /api/v1/reports/schedules/[id]   — remove the schedule. Past
 *                                            report_runs keep their
 *                                            schedule_id via ON DELETE
 *                                            SET NULL so history stays
 *                                            traceable.
 */
export const GET = withAuth(
  withPermission('reports', 'view_dashboard', async (_req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new NotFoundError('Report schedule');
      const row = await getReportSchedule(id, ctx.portId);
      return NextResponse.json({ data: row });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PATCH = withAuth(
  withPermission('reports', 'export', async (req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new NotFoundError('Report schedule');
      const body = await parseBody(req, updateReportScheduleSchema);
      const row = await updateReportSchedule(id, body, {
        portId: ctx.portId,
        meta: {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      });
      return NextResponse.json({ data: row });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('reports', 'export', async (_req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new NotFoundError('Report schedule');
      await deleteReportSchedule(id, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
