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 {
  pgCreatePaymentSchedule,
  pgListPaymentSchedulesByObligation,
} from '@/lib/postgres/expense-advanced';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ obligationId: string }> }
) {
  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 { obligationId } = await params;
    const schedules = await pgListPaymentSchedulesByObligation(obligationId);
    return NextResponse.json({ items: schedules }, { status: 200 });
  } catch (error) {
    console.error('Error listing payment schedules:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ obligationId: string }> }
) {
  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 { obligationId } = await params;
    const body = await request.json();

    if (!body?.dueDate || !body?.amount) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const schedule = await pgCreatePaymentSchedule({
      obligationId,
      dueDate: String(body.dueDate),
      amount: Number(body.amount),
      paymentMethod: body.paymentMethod ? String(body.paymentMethod) : 'bank',
      status: body.status || 'pending',
      paidAmount: Number(body.paidAmount || 0),
    });

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