import { NextRequest, NextResponse } from 'next/server';
import {
  pgBatchAddBankTransactions,
  pgGetBankReconciliationPeriodById,
} from '@/lib/postgres/bank-reconciliation';
import type { BankTransaction } from '@/lib/types';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const period = await pgGetBankReconciliationPeriodById(id);
    if (!period) {
      return NextResponse.json(
        { error: 'Reconciliation period not found' },
        { status: 404 }
      );
    }

    const body = await request.json().catch(() => ({}));
    const transactions = Array.isArray(body?.transactions) ? body.transactions : [];

    if (transactions.length === 0) {
      return NextResponse.json(
        { error: 'transactions array is required' },
        { status: 400 }
      );
    }

    const normalized = transactions.map((txn: any) => ({
      reconciliationPeriodId: period.id,
      bankAccountId: period.bankAccountId,
      transactionDate: String(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 invalid = normalized.some(
      (txn) => !txn.transactionDate || !Number.isFinite(txn.amount) || txn.amount <= 0
    );

    if (invalid) {
      return NextResponse.json(
        { error: 'Each transaction must include valid transactionDate and positive amount' },
        { status: 400 }
      );
    }

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

    return NextResponse.json(
      {
        periodId: period.id,
        importedCount: created.length,
        items: created,
      },
      { status: 201 }
    );
  } catch (error) {
    console.error('Error importing statement transactions:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Internal Server Error' },
      { status: 500 }
    );
  }
}
