import { useMemo } from 'react';
import { usePaymentHistory } from '@/services/payment';
import { useWalletInstallments } from '@/services/bnpl';
import type { PaymentTransactionStatus } from '@/services/payment/types';

export interface WalletHistoryRow {
  key: string;
  amountIrr: string;
  createdAt: string;
  status: PaymentTransactionStatus;
  bookingId: number | null;
}

/**
 * Merges the two independent seams a wallet history/receipt row can come from — card transactions
 * (`services/payment`, REQ-047) and each settled BNPL plan's own down-payment leg (`services/bnpl`) — into
 * one newest-first list. Shared by the wallet «پرداخت‌ها» and «رسیدها» tabs so the merge logic lives once.
 * Degrades gracefully: either source failing alone still renders the other's rows.
 */
export function useWalletHistoryRows() {
  const paymentHistory = usePaymentHistory();
  const walletInstallments = useWalletInstallments();

  const rows = useMemo<WalletHistoryRow[]>(() => {
    const cardRows: WalletHistoryRow[] = (paymentHistory.data ?? []).map((row) => ({
      key: `card-${row.transactionId}`,
      amountIrr: row.amountIrr,
      createdAt: row.createdAt,
      status: row.status,
      bookingId: row.bookingId,
    }));
    const bnplRows: WalletHistoryRow[] = (walletInstallments.data ?? []).map((plan) => {
      const downPayment = plan.installments.find((i) => i.kind === 'down_payment');
      return {
        key: `bnpl-${plan.bnplTransactionId}`,
        amountIrr: downPayment?.amountIrr ?? '0',
        createdAt: plan.createdAt,
        status: 'succeeded' as const,
        bookingId: plan.bookingId,
      };
    });
    return [...cardRows, ...bnplRows].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
  }, [paymentHistory.data, walletInstallments.data]);

  return {
    rows,
    isLoading: paymentHistory.isLoading || walletInstallments.isLoading,
    bothErrored: paymentHistory.isError && walletInstallments.isError,
    refetch: () => {
      paymentHistory.refetch();
      walletInstallments.refetch();
    },
  };
}
