import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { exportPdf } from '@/lib/services/expense-export';
import { listExpensesSchema } from '@/lib/validators/expenses';

export const POST = withAuth(
  withPermission('expenses', 'view', async (req, ctx) => {
    try {
      const body = await req.json().catch(() => ({}));
      const query = listExpensesSchema.parse(body);
      const pdf = await exportPdf(ctx.portId, query);

      return new NextResponse(Buffer.from(pdf), {
        status: 200,
        headers: {
          'Content-Type': 'application/pdf',
          'Content-Disposition': `attachment; filename="expenses-${Date.now()}.pdf"`,
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
