import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { previewBody } from '@/lib/services/document-sends.service';
import { previewBodySchema } from '@/lib/validators/document-sends';

/**
 * POST /api/v1/document-sends/preview
 *
 * Renders a body for the dry-run UI without actually sending. Returns the
 * sanitized HTML, the post-merge markdown, and the list of unresolved
 * `{{tokens}}` so the UI can block submit until the rep fills them in
 * (§14.7 mitigation).  Gated on `email.view` (auditor-A3 §4).
 */
export const POST = withAuth(
  withPermission('email', 'view', async (req, ctx) => {
    try {
      const input = await parseBody(req, previewBodySchema);
      const result = await previewBody(
        ctx.portId,
        input.documentKind,
        input.recipient,
        input.customBodyMarkdown ?? null,
        { berthId: input.berthId, brochureLabel: input.brochureId },
      );
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
