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 { pgListExpenseDocuments } from '@/lib/postgres/expense-recurring';

export async function GET(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 status = request.nextUrl.searchParams.get('status') || undefined;
    const page = Number(request.nextUrl.searchParams.get('page') || 1);
    const pageSize = Number(request.nextUrl.searchParams.get('pageSize') || 50);
    const periodYear = request.nextUrl.searchParams.get('periodYear');
    const periodMonth = request.nextUrl.searchParams.get('periodMonth');
    const templateId = request.nextUrl.searchParams.get('templateId') || undefined;

    const result = await pgListExpenseDocuments({
      status: status as any,
      page,
      pageSize,
      periodYear: periodYear ? Number(periodYear) : undefined,
      periodMonth: periodMonth ? Number(periodMonth) : undefined,
      templateId,
    });

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