import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { hasEmployeePermission } from '@/lib/employee-permissions';
import { pgGetSettings } from '@/lib/postgres/data-access';
import { pgGenerateExpenseDocumentsFromTemplates } from '@/lib/postgres/expense-recurring';

export async function POST(request: NextRequest) {
  const session = await getSession();
  const settings = await pgGetSettings();
  if (!session?.user || (!hasEmployeePermission(session.user, settings, 'admin.accounting') && !hasEmployeePermission(session.user, settings, 'admin.expense-recurring'))) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await request.json().catch(() => ({}));
    const result = await pgGenerateExpenseDocumentsFromTemplates({
      asOfDate: body?.asOfDate ? String(body.asOfDate) : undefined,
      actor: session.user.name || session.user.id,
    });

    return NextResponse.json(result, { status: 200 });
  } catch (error) {
    console.error('Error generating recurring expense documents:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
