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

/**
 * POST /api/v1/document-sends/brochure
 *
 * Sends a brochure (default or specified) to a client recipient. Same
 * sanitization + audit-row pipeline as the berth-pdf endpoint.
 *
 * Gated on `email.send` so the lowest-privilege role at a port (which
 * has only `email.view`) can no longer fire nodemailer at arbitrary
 * recipients. The 50/user/hour rate-limit was previously the only
 * restriction (auditor-A3 §4).
 */
export const POST = withAuth(
  withPermission('email', 'send', async (req, ctx) => {
    try {
      const input = await parseBody(req, sendBrochureSchema);
      const result = await sendBrochure({
        portId: ctx.portId,
        brochureId: input.brochureId,
        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);
    }
  }),
);
