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

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

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

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

    const obligation = await pgCreateExpenseObligation({
      documentId,
      contractId: body.contractId ? String(body.contractId) : undefined,
      templateId: body.templateId ? String(body.templateId) : undefined,
      periodStart: String(body.periodStart),
      periodEnd: String(body.periodEnd),
      grossAmount: Number(body.grossAmount),
      currencyCode: body.currencyCode ? String(body.currencyCode) : undefined,
      basis: body.basis || 'cash',
      recognitionDate: body.recognitionDate ? String(body.recognitionDate) : undefined,
      settlementDate: body.settlementDate ? String(body.settlementDate) : undefined,
      status: body.status || 'pending',
      reversalObligationId: body.reversalObligationId ? String(body.reversalObligationId) : undefined,
      createdBy: session.user.name || session.user.id,
    });

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