import { useQuery } from '@tanstack/react-query';
import { bnplApi } from '../apis';
import { bnplKeys } from '../keys';
import {
  BNPL_ORDER_POLL_BASE_MS,
  BNPL_ORDER_POLL_GROWTH,
  BNPL_ORDER_POLL_MAX_ATTEMPTS,
  BNPL_ORDER_POLL_MAX_MS,
} from '../constants';
import { isTerminalBnplStatus } from '../types';

/**
 * The BNPL order read + settle poll after the provider return. "Received ≠ settled" — settlement is not
 * instant, so this polls with **geometric backoff** (base → ×growth → cap) and **stops** on any terminal
 * status (`settled`/`reverted`/`cancelled`/`failed`) or after a bounded number of attempts — never a tight
 * loop. The return surface offers a manual re-check once the budget is spent.
 */
export function useBnplOrder(bookingRequestId: number | undefined, options?: { enabled?: boolean }) {
  return useQuery({
    queryKey: bnplKeys.order(bookingRequestId ?? -1),
    queryFn: () => bnplApi.getBnplOrder(bookingRequestId as number),
    enabled: (options?.enabled ?? true) && bookingRequestId != null && bookingRequestId > 0,
    refetchInterval: (query) => {
      const order = query.state.data;
      if (order && isTerminalBnplStatus(order.status)) return false;
      const attempt = query.state.dataUpdateCount;
      if (attempt >= BNPL_ORDER_POLL_MAX_ATTEMPTS) return false;
      return Math.min(BNPL_ORDER_POLL_BASE_MS * BNPL_ORDER_POLL_GROWTH ** attempt, BNPL_ORDER_POLL_MAX_MS);
    },
  });
}
