import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission, withRateLimit } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { requestGdprExport, listClientExports } from '@/lib/services/gdpr-export.service';

const requestSchema = z.object({
  /** When true, the bundle is emailed to the client once it finishes building. */
  emailToClient: z.boolean().optional().default(false),
  /** Optional override recipient (e.g. legal counsel). Skips the primary-email lookup. */
  emailOverride: z.string().email().optional().nullable(),
});

export const GET = withAuth(
  withPermission('clients', 'view', async (req, ctx, params) => {
    try {
      const rows = await listClientExports(params.id!, ctx.portId);
      return NextResponse.json({ data: rows });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission(
    'clients',
    'gdpr_export',
    withRateLimit('exports', async (req, ctx, params) => {
      try {
        const body = await parseBody(req, requestSchema);
        const result = await requestGdprExport({
          clientId: params.id!,
          portId: ctx.portId,
          requestedBy: ctx.userId,
          emailToClient: body.emailToClient,
          emailOverride: body.emailOverride ?? null,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        });
        return NextResponse.json({ data: result.export }, { status: 202 });
      } catch (error) {
        return errorResponse(error);
      }
    }),
  ),
);
