import { NextRequest, NextResponse } from 'next/server';
import {
  pgGetBankReconciliationPeriodById,
  pgGetBankTransactionsForPeriod,
  pgGetLedgerTransactionsForBankAccount,
  pgGetReconciliationMatchForBankTransaction,
  pgCreateReconciliationMatch,
  pgUpdateLedgerTransactionReconciliationStatus,
} from '@/lib/postgres/bank-reconciliation';

/**
 * POST /api/admin/bank-reconciliation/periods/[id]/manual-match
 * Body: { bankTransactionId: string, ledgerTransactionIds: string[], matchedBy: string, notes?: string }
 * 
 * Creates a manual match between one bank transaction and one or more ledger transactions.
 */
export async function POST(
  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 });
    }

    if (period.status === 'locked') {
      return NextResponse.json({ error: 'الفترة مقفلة ولا يمكن تعديلها' }, { status: 409 });
    }

    const body = await req.json();
    const { bankTransactionId, ledgerTransactionIds, matchedBy, notes } = body as {
      bankTransactionId: string;
      ledgerTransactionIds: string[];
      matchedBy: string;
      notes?: string;
    };

    if (!bankTransactionId || !Array.isArray(ledgerTransactionIds) || ledgerTransactionIds.length === 0 || !matchedBy) {
      return NextResponse.json(
        { error: 'bankTransactionId, ledgerTransactionIds[], and matchedBy are required' },
        { status: 400 }
      );
    }

    // Verify bank transaction belongs to this period
    const bankTransactions = await pgGetBankTransactionsForPeriod(periodId);
    const bankTxn = bankTransactions.find((b) => b.id === bankTransactionId);
    if (!bankTxn) {
      return NextResponse.json({ error: 'Bank transaction not found in this period' }, { status: 404 });
    }

    // Check if already matched
    const existing = await pgGetReconciliationMatchForBankTransaction(bankTransactionId);
    if (existing) {
      return NextResponse.json({ error: 'حركة البنك هذه مطابقة مسبقاً. قم بإلغاء المطابقة أولاً.' }, { status: 409 });
    }

    // Verify ledger transactions are available
    const availableLedger = await pgGetLedgerTransactionsForBankAccount(period.bankAccountId);
    const availableIds = new Set(availableLedger.map((l) => l.id));

    const missing = ledgerTransactionIds.filter((id) => !availableIds.has(id));
    if (missing.length > 0) {
      return NextResponse.json(
        { error: `حركات الدفتر التالية غير متاحة أو مطابقة مسبقاً: ${missing.join(', ')}` },
        { status: 409 }
      );
    }

    const matchType = ledgerTransactionIds.length > 1 ? 'multi-line' : 'manual';

    const match = await pgCreateReconciliationMatch({
      reconciliationPeriodId: periodId,
      bankTransactionId,
      ledgerTransactionIds,
      matchType,
      matchConfidence: 100,
      matchDate: new Date().toISOString(),
      matchedBy,
      notes: notes || 'مطابقة يدوية',
      status: 'matched',
    });

    // Mark all ledger transactions as reconciled
    for (const ledgerId of ledgerTransactionIds) {
      await pgUpdateLedgerTransactionReconciliationStatus(ledgerId, 'reconciled', periodId);
    }

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