import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { exportCsv } 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 csv = await exportCsv(ctx.portId, query);

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