/**
 * React hook for service health and log viewer data fetching.
 */
import { useCallback, useState } from "react";
import { fetchFail2BanLog, fetchServiceStatus } from "../api/config";
import type { Fail2BanLogResponse, ServiceStatusResponse } from "../types/config";

export interface UseServerHealthResult {
  status: ServiceStatusResponse | null;
  logData: Fail2BanLogResponse | null;
  error: string | null;
  refresh: () => Promise<void>;
}

/**
 * Load service status and fail2ban log data for the server health panel.
 */
export function useServerHealth(
  linesCount: number,
  filterValue: string,
): UseServerHealthResult {
  const [status, setStatus] = useState<ServiceStatusResponse | null>(null);
  const [logData, setLogData] = useState<Fail2BanLogResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async (): Promise<void> => {
    try {
      const [svcResult, logResult] = await Promise.allSettled([
        fetchServiceStatus(),
        fetchFail2BanLog(linesCount, filterValue || undefined),
      ]);

      if (svcResult.status === "fulfilled") {
        setStatus(svcResult.value);
      } else {
        setStatus(null);
      }

      if (logResult.status === "fulfilled") {
        setLogData(logResult.value);
        setError(null);
      } else {
        const reason: unknown = logResult.reason;
        setError(reason instanceof Error ? reason.message : "Failed to load log data.");
      }
    } catch (err: unknown) {
      const reason = err instanceof Error ? err.message : String(err);
      setError(reason);
    }
  }, [filterValue, linesCount]);

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