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 { exportCsv } from '@/lib/services/expense-export';
import { listExpensesSchema } from '@/lib/validators/expenses';
import { createAuditLog } from '@/lib/audit';

export const POST = withAuth(
  withPermission('expenses', 'view', async (req, ctx) => {
    try {
      const query = await parseBody(req, listExpensesSchema);
      const csv = await exportCsv(ctx.portId, query);

      void createAuditLog({
        userId: ctx.userId,
        portId: ctx.portId,
        action: 'send',
        entityType: 'expense_export',
        entityId: 'csv',
        metadata: { format: 'csv', filterCount: Object.keys(query).length, byteSize: csv.length },
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
        severity: 'warning',
      });

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