import { NextRequest, NextResponse } from 'next/server';
import {
  pgGetBankReconciliationPeriodById,
  pgGetAllLedgerTransactionsForBankAccount,
} from '@/lib/postgres/bank-reconciliation';

/**
 * GET /api/admin/bank-reconciliation/periods/[id]/ledger-transactions
 * Returns ALL ledger transactions (reconciled & unreconciled) for the bank account,
 * filtered to the period's date range.
 */
export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: periodId } = await params;

    const period = await pgGetBankReconciliationPeriodById(periodId);
    if (!period) {
      return NextResponse.json({ error: 'Period not found' }, { status: 404 });
    }

    const all = await pgGetAllLedgerTransactionsForBankAccount(period.bankAccountId);

    // Filter to the period's date range
    const filtered = all.filter(
      (lt) =>
        lt.transactionDate >= period.periodStartDate &&
        lt.transactionDate <= period.periodEndDate
    );

    return NextResponse.json(filtered, { status: 200 });
  } catch (error) {
    console.error('Error fetching ledger transactions for period:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
