import { useQuery } from '@tanstack/react-query';
import { useIsAuthenticated } from '@/hooks';
import { nurseBankApi } from '../apis';
import { bankKeys } from '../keys';
import { BANK_POLL_INTERVAL_MS, BANK_STALE_TIME } from '../constants';
import { deriveBankStatus, type NurseBankAccountDto } from '../types';

/**
 * The nurse's bank accounts (usually one primary). Polls **only while an account's ownership
 * inquiry is pending** so the pending→verified/mismatch transition appears without a manual
 * reload, then stops once every account has resolved.
 */
export function useNurseBankAccounts() {
  const isAuthenticated = useIsAuthenticated();
  return useQuery({
    queryKey: bankKeys.list(),
    queryFn: () => nurseBankApi.list(),
    enabled: isAuthenticated,
    staleTime: BANK_STALE_TIME,
    refetchInterval: (query) => {
      const accounts = (query.state.data ?? []) as NurseBankAccountDto[];
      return accounts.some((account) => deriveBankStatus(account) === 'pending') ? BANK_POLL_INTERVAL_MS : false;
    },
  });
}
