import { useEffect, useState } from "react";

import {
  fetchPolygonWorkerStatus,
  type PolygonWorkerStatus,
} from "./liveWorker";

export interface PolygonWorkerCapability {
  checked: boolean;
  available: boolean;
  status: PolygonWorkerStatus | null;
}

const initialCapability: PolygonWorkerCapability = {
  checked: false,
  available: false,
  status: null,
};

export function usePolygonWorkerCapability(): PolygonWorkerCapability {
  const [capability, setCapability] = useState(initialCapability);

  useEffect(() => {
    const controller = new AbortController();
    let timer: number | null = null;

    const poll = async () => {
      try {
        const status = await fetchPolygonWorkerStatus({ signal: controller.signal });
        if (controller.signal.aborted) return;
        setCapability({
          checked: true,
          available: status.available,
          status,
        });
      } catch {
        if (controller.signal.aborted) return;
        setCapability({
          checked: true,
          available: false,
          status: null,
        });
      } finally {
        if (!controller.signal.aborted) {
          timer = window.setTimeout(() => void poll(), 3_000);
        }
      }
    };

    void poll();
    return () => {
      controller.abort();
      if (timer !== null) window.clearTimeout(timer);
    };
  }, []);

  return capability;
}
