import { NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { documentTemplates, files } from '@/lib/db/schema/documents';
import { errorResponse, NotFoundError, ValidationError } from '@/lib/errors';
import { getStorageBackend } from '@/lib/storage';
import { detectFields } from '@/lib/services/document-field-detector';

/**
 * Phase 4 - Auto-detect signature/date/initials/name/email anchors in the
 * template's current source PDF and return suggested field placements.
 *
 * The detector (`src/lib/services/document-field-detector.ts`) scans each
 * page's text content via pdfjs-dist `getTextContent()` and matches anchors
 * against a regex pattern table. Returned `DetectedField[]` is in percent-
 * coords (0..100 of page dimensions), which the editor converts to its
 * own 0..1 marker coords before adding to the field map.
 *
 * Permission: `admin.manage_settings` - same gate as the editor itself.
 */
export const POST = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
    try {
      const template = await db.query.documentTemplates.findFirst({
        where: and(eq(documentTemplates.id, params.id!), eq(documentTemplates.portId, ctx.portId)),
      });
      if (!template) throw new NotFoundError('Template');
      if (!template.sourceFileId) {
        throw new ValidationError(
          'Template has no source PDF - upload one first via the Replace PDF button',
        );
      }

      const sourceFile = await db.query.files.findFirst({
        where: and(eq(files.id, template.sourceFileId), eq(files.portId, ctx.portId)),
      });
      if (!sourceFile) {
        throw new NotFoundError('Source PDF file row missing');
      }

      // Read the PDF blob from storage. Buffer the whole stream - the
      // detector needs a contiguous Buffer for pdfjs-dist, and template
      // source PDFs are capped at 10MB by the source-pdf upload route.
      const backend = await getStorageBackend();
      const stream = await backend.get(sourceFile.storagePath);
      const chunks: Buffer[] = [];
      for await (const chunk of stream) {
        chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : Buffer.from(chunk));
      }
      const pdfBuffer = Buffer.concat(chunks);

      const detected = await detectFields(pdfBuffer);

      return NextResponse.json({
        data: {
          fields: detected,
          totalAnchors: detected.length,
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
