import { NextResponse } from 'next/server';

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

// Gated on `email.view` so the lowest-privilege role at a port can no
// longer enumerate which clients have received which brochures / berth
// PDFs (auditor-A3 §4).
export const GET = withAuth(
  withPermission('email', 'view', async (req, ctx) => {
    try {
      const query = parseQuery(req, listSendsQuerySchema);
      const data = await listSends({
        portId: ctx.portId,
        clientId: query.clientId,
        interestId: query.interestId,
        berthId: query.berthId,
        limit: query.limit,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
