import { useQuery } from '@tanstack/react-query';
import { fetchNodeStatus, NodeStatusUnavailableError, type NodeStatus } from '../api';

const QK = ['dashboard', 'node-status'] as const;
const HEALTHY_INTERVAL_MS = 5_000;
const ERROR_BACKOFF_MS = 60_000;

/**
 * Polls /api/local/dashboard/node-status on a 5s interval, backing off
 * to 60s while the endpoint is failing (503 from an unconfigured
 * registry, network errors, etc.). Without backoff a misconfigured AAO
 * would hammer the endpoint every 5s forever.
 *
 * Phase B uses fixed-rate polling on both ends (server registry +
 * client refetch) — the server-side cadence is the source of truth and
 * the UI query just keeps the local cache fresh. Dynamic
 * visibility-aware polling (Open Question #1) is a Phase C concern.
 */
export function useNodeStatus() {
  const q = useQuery({
    queryKey: QK,
    queryFn: fetchNodeStatus,
    refetchInterval: (query) => (query.state.error ? ERROR_BACKOFF_MS : HEALTHY_INTERVAL_MS),
    // Don't retry-storm on 503: a single retry is enough to ride out a
    // transient blip; persistent failures should fall through to the
    // backoff above.
    retry: 1,
    staleTime: 0,
  });
  // Treat a "registry not configured" error as an empty list for
  // rendering purposes (the UI degrades gracefully) but keep isError
  // true so the backoff stays engaged.
  const isUnavailable = q.error instanceof NodeStatusUnavailableError;
  return {
    nodes: q.data ?? [],
    isLoading: q.isLoading,
    isError: q.isError && !isUnavailable,
    isUnavailable,
  };
}

export type { NodeStatus };
