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 {
  pgCreateRecurringExpenseTemplate,
  pgListRecurringExpenseTemplates,
} 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 result = await pgListRecurringExpenseTemplates({
      status: status as any,
      page,
      pageSize,
    });

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

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();

    if (!body?.name || !body?.expenseAccountCode || !body?.defaultAmount || !body?.frequency || !body?.startDate) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const created = await pgCreateRecurringExpenseTemplate({
      name: String(body.name),
      expenseItemId: body.expenseItemId ? String(body.expenseItemId) : undefined,
      expenseAccountCode: String(body.expenseAccountCode),
      payableAccountCode: String(body.payableAccountCode || '2130'),
      defaultAmount: Number(body.defaultAmount),
      currencyCode: body.currencyCode ? String(body.currencyCode) : undefined,
      frequency: body.frequency,
      intervalCount: Number(body.intervalCount || 1),
      startDate: String(body.startDate),
      dayOfMonth: body.dayOfMonth ? Number(body.dayOfMonth) : undefined,
      monthOfYear: body.monthOfYear ? Number(body.monthOfYear) : undefined,
      endDate: body.endDate ? String(body.endDate) : undefined,
      approvalPolicy: body.approvalPolicy || 'single_step',
      autoSubmitForApproval: Boolean(body.autoSubmitForApproval),
      status: body.status || 'active',
      notes: body.notes ? String(body.notes) : undefined,
      createdBy: session.user.name || session.user.id,
      nextRunDate: body.nextRunDate ? String(body.nextRunDate) : undefined,
    });

    return NextResponse.json(created, { status: 201 });
  } catch (error) {
    console.error('Error creating recurring expense template:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
