/**
 * React hook for polling blocklist schedule error state.
 */

import { useEffect, useRef, useState } from "react";
import { fetchSchedule } from "../api/blocklist";

const BLOCKLIST_POLL_INTERVAL_MS = 60_000;

export interface UseBlocklistStatusReturn {
  hasErrors: boolean;
}

/**
 * Poll `GET /api/blocklists/schedule` every 60 seconds to detect whether
 * the most recent blocklist import had errors.
 */
export function useBlocklistStatus(): UseBlocklistStatusReturn {
  const [hasErrors, setHasErrors] = useState(false);
  const abortRef = useRef<AbortController | null>(null);

  useEffect(() => {
    const poll = (): void => {
      abortRef.current?.abort();
      const controller = new AbortController();
      abortRef.current = controller;

      fetchSchedule(controller.signal)
        .then((info) => {
          if (controller.signal.aborted) {
            return;
          }
          setHasErrors(info.last_run_errors === true);
        })
        .catch(() => {
          // Silently swallow network errors — do not change indicator state.
        });
    };

    poll();
    const id = window.setInterval(poll, BLOCKLIST_POLL_INTERVAL_MS);
    return (): void => {
      abortRef.current?.abort();
      window.clearInterval(id);
    };
  }, []);

  return { hasErrors };
}
