import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { exportClientPdf } from '@/lib/services/record-export';

export const POST = withAuth(
  withPermission('clients', 'view', async (req, ctx, params) => {
    try {
      const pdfBytes = await exportClientPdf(params.id!, ctx.portId);
      return new NextResponse(Buffer.from(pdfBytes), {
        status: 200,
        headers: {
          'Content-Type': 'application/pdf',
          'Content-Disposition': 'attachment; filename="client-summary.pdf"',
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
