import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { detectFields } from '@/lib/services/document-field-detector';
import { isPdfMagic } from '@/lib/services/berth-pdf-parser';

/**
 * Phase 4 - Auto-detect anchor scanner endpoint.
 *
 * POST `/api/v1/documents/auto-detect-fields`
 *
 * Body: multipart/form-data
 *   - file: the source PDF the rep just uploaded
 *
 * Returns: `{ data: { fields: DetectedField[] } }` - seed state for the
 * drag-drop overlay. Empty array when the PDF has no extractable text
 * (image-only scan) - the dialog falls back to manual placement
 * without an error toast.
 *
 * Permission: documents.send_for_signing - the only flow that calls
 * this endpoint is the upload-for-signing dialog, which already
 * requires that bit. Reusing it here means a custom role with the
 * upload bit but no send bit can't dry-run the detector to pull
 * structural metadata out of a contract before sending.
 */
const MAX_PDF_BYTES = 50 * 1024 * 1024;

export const POST = withAuth(
  withPermission('documents', 'send_for_signing', async (req) => {
    try {
      const form = await req.formData();
      const file = form.get('file');
      if (!file || !(file instanceof File)) {
        throw new ValidationError('Missing file');
      }
      if (file.size > MAX_PDF_BYTES) {
        throw new ValidationError(`File exceeds ${MAX_PDF_BYTES / 1024 / 1024} MB cap`);
      }
      const buffer = Buffer.from(await file.arrayBuffer());
      if (!isPdfMagic(buffer)) {
        throw new ValidationError('Uploaded file is not a PDF');
      }
      const fields = await detectFields(buffer);
      return NextResponse.json({ data: { fields } });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
