import { NextRequest, NextResponse } from 'next/server';
import {
  pgGetBankTransactionsForPeriod,
  pgBatchAddBankTransactions,
} from '@/lib/postgres/bank-reconciliation';
import type { BankTransaction } 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 transactions = await pgGetBankTransactionsForPeriod(periodId);

    return NextResponse.json(
      { items: transactions, total: transactions.length },
      { status: 200 }
    );
  } catch (error) {
    console.error('Error fetching bank transactions:', 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 { periodId, bankAccountId, transactions } = body;

    if (!periodId || !bankAccountId || !Array.isArray(transactions) || transactions.length === 0) {
      return NextResponse.json(
        { error: 'Invalid request body' },
        { status: 400 }
      );
    }

    const normalized = transactions.map((txn: any) => ({
      reconciliationPeriodId: periodId,
      bankAccountId,
      transactionDate: txn.transactionDate,
      amount: Number(txn.amount),
      direction: txn.direction || 'inward',
      description: txn.description || null,
      bankReference: txn.bankReference || null,
      type: txn.type || 'other',
      currencyCode: txn.currencyCode || null,
    }));

    const created = await pgBatchAddBankTransactions(
      normalized as Omit<BankTransaction, 'id' | 'createdAt' | 'updatedAt'>[]
    );

    return NextResponse.json(
      { items: created, total: created.length },
      { status: 201 }
    );
  } catch (error) {
    console.error('Error adding bank transactions:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
