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 {
  pgCreateRecurringExpenseContract,
  pgGetRecurringContractById,
  pgListRecurringContracts,
  pgUpdateRecurringContract,
} from '@/lib/postgres/expense-advanced';

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 templateId = request.nextUrl.searchParams.get('templateId') || undefined;
    const page = Number(request.nextUrl.searchParams.get('page') || 1);
    const pageSize = Number(request.nextUrl.searchParams.get('pageSize') || 50);

    const result = await pgListRecurringContracts({
      status: status as any,
      templateId: templateId as any,
      page,
      pageSize,
    });

    return NextResponse.json(result, { status: 200 });
  } catch (error) {
    console.error('Error listing recurring contracts:', 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?.contractDate || !body?.startDate) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const created = await pgCreateRecurringExpenseContract({
      name: String(body.name),
      templateId: body.templateId ? String(body.templateId) : undefined,
      vendorId: body.vendorId ? String(body.vendorId) : undefined,
      contractDate: String(body.contractDate),
      startDate: String(body.startDate),
      endDate: body.endDate ? String(body.endDate) : undefined,
      renewalTerms: body.renewalTerms || 'manual_renew',
      escalationPolicy: body.escalationPolicy || 'none',
      escalationValue: body.escalationValue ? Number(body.escalationValue) : undefined,
      allocationStrategy: body.allocationStrategy || 'none',
      status: body.status || 'active',
      notes: body.notes ? String(body.notes) : undefined,
      createdBy: session.user.name || session.user.id,
    });

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