import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody, parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { createReportSchedule, listReportSchedules } from '@/lib/services/report-schedules.service';
import { createReportScheduleSchema, listReportSchedulesSchema } from '@/lib/validators/reports';

/**
 * GET  /api/v1/reports/schedules
 *   List the port's recurring schedules. Filterable by enabled flag +
 *   templateId. Powers the /reports/schedules management surface.
 *
 * POST /api/v1/reports/schedules
 *   Create a recurring schedule. `nextRunAt` is computed server-side from
 *   the cadence; clients don't pass it. Recipients travel as a small JSON
 *   list — no relational expansion needed at v1 cadences/list sizes.
 */
export const GET = withAuth(
  withPermission('reports', 'view_dashboard', async (req, ctx) => {
    try {
      const query = parseQuery(req, listReportSchedulesSchema);
      const result = await listReportSchedules(ctx.portId, query);
      return NextResponse.json({
        data: result.data,
        total: result.total,
        hasMore: result.hasMore,
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('reports', 'export', async (req, ctx) => {
    try {
      const body = await parseBody(req, createReportScheduleSchema);
      const row = await createReportSchedule(body, {
        portId: ctx.portId,
        meta: {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      });
      return NextResponse.json({ data: row }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
