/**
 * React hook for jail state mutations.
 *
 * Handles write operations (start, stop, reload, setIdle, addIp, removeIp, toggleIgnoreSelf).
 * Each operation calls the API and then invokes `onSuccess` to trigger a data refresh.
 */

import { useCallback } from "react";
import {
  addIgnoreIp,
  delIgnoreIp,
  reloadJail,
  setJailIdle,
  startJail,
  stopJail,
  toggleIgnoreSelf as toggleIgnoreSelfApi,
} from "../api/jails";

export interface UseJailCommandsResult {
  addIp: (ip: string) => Promise<void>;
  removeIp: (ip: string) => Promise<void>;
  toggleIgnoreSelf: (on: boolean) => Promise<void>;
  start: () => Promise<void>;
  stop: () => Promise<void>;
  reload: () => Promise<void>;
  setIdle: (on: boolean) => Promise<void>;
}

/**
 * Manage mutations for a jail (start, stop, reload, etc.).
 * Calls `onSuccess` after each operation to trigger data refresh.
 *
 * @param name - The name of the jail.
 * @param onSuccess - Callback to invoke after each successful operation (typically to refresh data).
 * @returns Mutation functions.
 */
export function useJailCommands(
  name: string,
  onSuccess: () => void,
): UseJailCommandsResult {
  const addIp = useCallback(
    async (ip: string): Promise<void> => {
      await addIgnoreIp(name, ip);
      onSuccess();
    },
    [name, onSuccess],
  );

  const removeIp = useCallback(
    async (ip: string): Promise<void> => {
      await delIgnoreIp(name, ip);
      onSuccess();
    },
    [name, onSuccess],
  );

  const toggleIgnoreSelf = useCallback(
    async (on: boolean): Promise<void> => {
      await toggleIgnoreSelfApi(name, on);
      onSuccess();
    },
    [name, onSuccess],
  );

  const start = useCallback(async (): Promise<void> => {
    await startJail(name);
    onSuccess();
  }, [name, onSuccess]);

  const stop = useCallback(async (): Promise<void> => {
    await stopJail(name);
    onSuccess();
  }, [name, onSuccess]);

  const reload = useCallback(async (): Promise<void> => {
    await reloadJail(name);
    onSuccess();
  }, [name, onSuccess]);

  const setIdle = useCallback(async (on: boolean): Promise<void> => {
    await setJailIdle(name, on);
    onSuccess();
  }, [name, onSuccess]);

  return {
    addIp,
    removeIp,
    toggleIgnoreSelf,
    start,
    stop,
    reload,
    setIdle,
  };
}
