import { useQuery } from "@tanstack/react-query";

const BASE_URL = (import.meta.env.VITE_API_URL ?? "").replace(/\/$/, "");

/**
 * Lightweight relay-connection liveness probe for the topbar indicator.
 *
 * Pass 1 has no viewer WebSocket yet, so "live" here means the GC server is
 * reachable. It polls the unauthenticated `/health` route every 15s. This is a
 * deliberately cheap signal — the real relay/WS liveness lands with the viewer
 * in a later pass.
 */
export function useRelayStatus(): { live: boolean; checking: boolean } {
  const { data, isLoading, isError } = useQuery({
    queryKey: ["health"],
    queryFn: async ({ signal }) => {
      const res = await fetch(`${BASE_URL}/health`, { signal });
      if (!res.ok) throw new Error(`health ${res.status}`);
      return true;
    },
    refetchInterval: 15_000,
    refetchOnWindowFocus: true,
    retry: 1,
    staleTime: 10_000,
  });

  return { live: data === true && !isError, checking: isLoading };
}
