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 {
  pgCreateExpensePosting,
  pgListPostingsByObligation,
} 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 postings = await pgListPostingsByObligation(obligationId);
    return NextResponse.json({ items: postings }, { status: 200 });
  } catch (error) {
    console.error('Error listing postings:', 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?.debitAccount || !body?.creditAccount || !body?.amount || !body?.postingDate) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const posting = await pgCreateExpensePosting({
      obligationId,
      documentId: body.documentId ? String(body.documentId) : undefined,
      journalEntryId: body.journalEntryId ? String(body.journalEntryId) : undefined,
      debitAccount: String(body.debitAccount),
      creditAccount: String(body.creditAccount),
      amount: Number(body.amount),
      postingDate: String(body.postingDate),
      postingType: body.postingType || 'regular',
      status: body.status || 'pending',
      reversalPostingId: body.reversalPostingId ? String(body.reversalPostingId) : undefined,
      reversalReason: body.reversalReason ? String(body.reversalReason) : undefined,
      createdBy: session.user.name || session.user.id,
    });

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