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 { pgCreateExpensePayment, pgListExpensePayments } from '@/lib/postgres/expense-recurring';

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 } = await params;
    const items = await pgListExpensePayments(id);
    return NextResponse.json({ items }, { status: 200 });
  } catch (error) {
    console.error('Error listing expense payments:', 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 } = await params;
    const body = await request.json();

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

    const result = await pgCreateExpensePayment(id, {
      paymentDate: body.paymentDate ? String(body.paymentDate) : new Date().toISOString(),
      amount: Number(body.amount),
      paymentMethod: body.paymentMethod,
      accountCode: String(body.accountCode),
      referenceNumber: body.referenceNumber ? String(body.referenceNumber) : undefined,
      notes: body.notes ? String(body.notes) : undefined,
      createdBy: session.user.name || session.user.id,
    });

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