/**
 * React hook for loading the jail config inventory.
 */

import { useCallback, useState } from "react";
import { fetchJailConfigs, reloadConfig, updateJailConfig } from "../api/config";
import { useListData } from "./useListData";
import type { JailConfig, JailConfigUpdate, JailConfigListResponse } from "../types/config";
import type { FetchError } from "../types/api";

export interface UseJailConfigsResult {
  jails: JailConfig[];
  total: number;
  loading: boolean;
  error: FetchError | null;
  refresh: () => void;
  updateJail: (name: string, update: JailConfigUpdate) => Promise<void>;
  reloadAll: () => Promise<void>;
}

/**
 * Load all jail configs and expose update controls.
 */
export function useJailConfigs(): UseJailConfigsResult {
  const [total, setTotal] = useState(0);

  const fetcher = useCallback(
    (signal: AbortSignal) => fetchJailConfigs(signal),
    [],
  );

  const selector = useCallback((response: JailConfigListResponse) => response.items, []);

  const onSuccess = useCallback((response: JailConfigListResponse) => {
    setTotal(response.total);
  }, []);

  const { items: jails, loading, error, refresh } = useListData<JailConfigListResponse, JailConfig>({
    fetcher,
    selector,
    errorMessage: "Failed to fetch jail configs",
    onSuccess,
  });

  const updateJail = useCallback(
    async (name: string, update: JailConfigUpdate): Promise<void> => {
      await updateJailConfig(name, update);
      refresh();
    },
    [refresh],
  );

  const reloadAll = useCallback(async (): Promise<void> => {
    await reloadConfig();
    refresh();
  }, [refresh]);

  return { jails, total, loading, error, refresh, updateJail, reloadAll };
}
