import { NextResponse } from 'next/server';

import { withAuth, withPermission, withRateLimit } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getExportDownloadUrl } from '@/lib/services/gdpr-export.service';
import { createAuditLog } from '@/lib/audit';

/**
 * Returns a fresh signed URL for an existing GDPR export. Staff use this
 * from the admin UI; the email path embeds its own signed URL.
 *
 * Every call writes a `view` audit row at 'warning' severity - GDPR
 * exports contain the entire personal data of a client and a fresh
 * presigned URL would let the operator download it; we want a clear
 * trail of who pulled what when.
 */
export const GET = withAuth(
  withPermission(
    'clients',
    'gdpr_export',
    withRateLimit('exports', async (req, ctx, params) => {
      try {
        const url = await getExportDownloadUrl(params.exportId!, ctx.portId);

        void createAuditLog({
          userId: ctx.userId,
          portId: ctx.portId,
          action: 'view',
          entityType: 'gdpr_export',
          entityId: params.exportId!,
          metadata: { clientId: params.id ?? null, urlIssued: true },
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
          severity: 'warning',
        });

        return NextResponse.json({ data: { url } });
      } catch (error) {
        return errorResponse(error);
      }
    }),
  ),
);
