/**
 * `useServerStatus` hook.
 *
 * Fetches and periodically refreshes the fail2ban server health snapshot
 * from `GET /api/dashboard/status`.  Also refetches on window focus so the
 * status is always fresh when the user returns to the tab.
 */

import { useCallback } from "react";
import { fetchServerStatus } from "../api/dashboard";
import { usePolledData } from "./usePolledData";
import type { ServerStatus, ServerStatusResponse } from "../types/server";
import type { FetchError } from "../types/api";

/** How often to poll the status endpoint (milliseconds). */
const POLL_INTERVAL_MS = 30_000;

/** Return value of the {@link useServerStatus} hook. */
export interface UseServerStatusResult {
  /** The most recent server status snapshot, or `null` before the first fetch. */
  status: ServerStatus | null;
  /** Whether a fetch is currently in flight. */
  loading: boolean;
  /** Error message string when the last fetch failed, otherwise `null`. */
  error: FetchError | null;
  /** Manually trigger a refresh immediately. */
  refresh: () => void;
}

/**
 * Poll `GET /api/dashboard/status` every 30 seconds and on window focus.
 *
 * @returns Current status, loading state, error, and a `refresh` callback.
 */
export function useServerStatus(): UseServerStatusResult {
  const fetcher = useCallback(
    (signal: AbortSignal) => fetchServerStatus(signal),
    [],
  );

  const selector = useCallback((response: ServerStatusResponse) => response.status, []);

  const { data: status, loading, error, refresh } = usePolledData<ServerStatusResponse, ServerStatus>({
    fetcher,
    selector,
    errorMessage: "Failed to fetch server status",
    pollInterval: POLL_INTERVAL_MS,
    refetchOnWindowFocus: true,
  });

  return { status, loading, error, refresh };
}
