import { useQuery } from '@tanstack/react-query';
import { paymentApi } from '../apis';
import { paymentKeys } from '../keys';
import {
  PAYMENT_OUTCOME_POLL_BASE_MS,
  PAYMENT_OUTCOME_POLL_GROWTH,
  PAYMENT_OUTCOME_POLL_MAX_ATTEMPTS,
  PAYMENT_OUTCOME_POLL_MAX_MS,
} from '../constants';
import { isTerminalPaymentOutcome } from '../types';

/**
 * The pending-callback poll. "PSP received ≠ cash in bank" — a pending state after the gateway return is
 * normal, so this polls **with geometric backoff** (base → ×growth → cap) and **stops** on any terminal
 * outcome or after a bounded number of attempts — never a tight loop, never hammering the endpoint. The
 * return surface offers a manual re-check once the budget is spent. `dataUpdateCount` is the attempt
 * counter (it increments per successful fetch, which is exactly the cadence backoff should follow).
 */
export function usePaymentOutcome(bookingRequestId: number | undefined, options?: { enabled?: boolean }) {
  return useQuery({
    queryKey: paymentKeys.outcome(bookingRequestId ?? -1),
    queryFn: () => paymentApi.getPaymentOutcome(bookingRequestId as number),
    enabled: (options?.enabled ?? true) && bookingRequestId != null && bookingRequestId > 0,
    refetchInterval: (query) => {
      const outcome = query.state.data;
      if (outcome && isTerminalPaymentOutcome(outcome)) return false;
      const attempt = query.state.dataUpdateCount;
      if (attempt >= PAYMENT_OUTCOME_POLL_MAX_ATTEMPTS) return false;
      return Math.min(
        PAYMENT_OUTCOME_POLL_BASE_MS * PAYMENT_OUTCOME_POLL_GROWTH ** attempt,
        PAYMENT_OUTCOME_POLL_MAX_MS,
      );
    },
  });
}
