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

// Gated on `expenses.export` for parity with sibling export routes
// (auditor-A3 §5). Hard `isSuperAdmin` check used to lock out port
// admins who held expenses.export = true.
export const POST = withAuth(
  withPermission('expenses', 'export', async (req, ctx) => {
    try {
      const query = await parseBody(req, listExpensesSchema);
      const pdf = await exportParentCompany(ctx.portId, query);

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