import { NextRequest, NextResponse } from 'next/server';
import {
  pgAddBankReconciliationDifference,
  pgGetBankReconciliationDifferencesForPeriod,
  pgResolveBankReconciliationDifference,
} from '@/lib/postgres/bank-reconciliation';
import type { BankReconciliationDifference, BankDifferenceType } from '@/lib/types';

export async function GET(request: NextRequest) {
  try {
    const periodId = request.nextUrl.searchParams.get('periodId');

    if (!periodId) {
      return NextResponse.json(
        { error: 'periodId is required' },
        { status: 400 }
      );
    }

    const differences = await pgGetBankReconciliationDifferencesForPeriod(periodId);

    return NextResponse.json(
      { items: differences, total: differences.length },
      { status: 200 }
    );
  } catch (error) {
    console.error('Error fetching bank reconciliation differences:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    const {
      reconciliationPeriodId,
      type,
      amount,
      description,
      bankTransactionId,
      ledgerTransactionId,
      notes,
    } = body;

    if (!reconciliationPeriodId || !type || amount === undefined) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      );
    }

    const difference = await pgAddBankReconciliationDifference({
      reconciliationPeriodId,
      type: type as BankDifferenceType,
      amount: Number(amount),
      description,
      bankTransactionId,
      ledgerTransactionId,
      resolutionType: 'pending',
      notes,
    } as Omit<BankReconciliationDifference, 'id' | 'createdAt' | 'updatedAt'>);

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