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 {
  pgCreateExpenseAllocation,
  pgListAllocationsByObligation,
} 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 allocations = await pgListAllocationsByObligation(obligationId);
    return NextResponse.json({ items: allocations }, { status: 200 });
  } catch (error) {
    console.error('Error listing allocations:', 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?.allocationType || !body?.allocationTargetId || !body?.percentage || !body?.amount) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const allocation = await pgCreateExpenseAllocation({
      obligationId,
      allocationType: String(body.allocationType),
      allocationTargetId: String(body.allocationTargetId),
      allocationTargetName: body.allocationTargetName ? String(body.allocationTargetName) : undefined,
      percentage: Number(body.percentage),
      amount: Number(body.amount),
      createdBy: session.user.name || session.user.id,
    });

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