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 { getQueue } from '@/lib/queue';
import { createReportRun, listReportRuns } from '@/lib/services/report-runs.service';
import { createReportRunSchema, listReportRunsSchema } from '@/lib/validators/reports';

/**
 * GET  /api/v1/reports/runs
 *   List the port's report-run history. Filterable by kind / status /
 *   templateId. Used by the /reports/runs surface for "re-run" and
 *   "re-email" affordances.
 *
 * POST /api/v1/reports/runs
 *   Queue a new render. Inserts a `pending` row; the BullMQ render worker
 *   (P3) picks it up. `templateId` is optional — anonymous one-off runs
 *   (e.g. the dashboard's "Export as PDF" button after migration) skip the
 *   template anchor and just pass a config directly.
 */
export const GET = withAuth(
  withPermission('reports', 'view_dashboard', async (req, ctx) => {
    try {
      const query = parseQuery(req, listReportRunsSchema);
      const result = await listReportRuns(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, createReportRunSchema);
      const row = await createReportRun(body, {
        portId: ctx.portId,
        triggeredBy: 'user',
        triggeredByUserId: ctx.userId,
        meta: {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      });
      // P3: hand off to the BullMQ render worker. Failure to enqueue
      // doesn't abort the create — the schedule poll picks up pending
      // rows on the next tick as a safety net.
      try {
        await getQueue('reports').add(
          'report-run-render',
          { reportRunId: row.id },
          { jobId: `report-run-render:${row.id}` },
        );
      } catch (queueErr) {
        // Logged but swallowed so the API still returns 201 with the row.
        // The pending row stays visible in /reports/runs so the rep can
        // see it queued; a future ops job can rescue stuck pendings.
        const { logger } = await import('@/lib/logger');
        logger.error(
          { queueErr, reportRunId: row.id },
          'Failed to enqueue render after createReportRun',
        );
      }
      return NextResponse.json({ data: row }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
