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

import { usePolledData } from "./usePolledData";
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.
 *
 * Polling pauses when the page is hidden and resumes immediately when visible.
 */
export function useBlocklistStatus(): UseBlocklistStatusReturn {
  const { data } = usePolledData({
    fetcher: (signal) => fetchSchedule(signal),
    selector: (response) => response.last_run_errors === true,
    errorMessage: "Failed to fetch blocklist schedule",
    pollInterval: BLOCKLIST_POLL_INTERVAL_MS,
    pauseWhenHidden: true,
  });

  return { hasErrors: data ?? false };
}
