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 { sendBerthPdf } from '@/lib/services/document-sends.service';
import { sendBerthPdfSchema } from '@/lib/validators/document-sends';

/**
 * POST /api/v1/document-sends/berth-pdf
 *
 * Sends the active per-berth PDF version to a client recipient. The body
 * markdown goes through the merge-field expander + sanitizer
 * (`renderEmailBody`) before reaching nodemailer (§14.7 critical mitigation:
 * body XSS).  Gated on `email.send` (auditor-A3 §4).
 */
export const POST = withAuth(
  withPermission('email', 'send', async (req, ctx) => {
    try {
      const input = await parseBody(req, sendBerthPdfSchema);
      const result = await sendBerthPdf({
        portId: ctx.portId,
        berthId: input.berthId,
        recipient: input.recipient,
        customBodyMarkdown: input.customBodyMarkdown,
        sentBy: ctx.userId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
