import { NextResponse } from 'next/server';

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

export const POST = withAuth(async (req, ctx) => {
  try {
    if (!ctx.isSuperAdmin) {
      return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
    }

    const body = await req.json().catch(() => ({}));
    const query = listExpensesSchema.parse(body);
    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);
  }
});
