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

import { useEffect, 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);

  useEffect(() => {
    let cancelled = false;

    const poll = (): void => {
      fetchSchedule()
        .then((info) => {
          if (!cancelled) {
            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 => {
      cancelled = true;
      window.clearInterval(id);
    };
  }, []);

  return { hasErrors };
}
