/**
 * React hook for performing jail-specific configuration operations.
 */
import { useCallback } from "react";
import {
  addLogPath,
  deleteLogPath,
  fetchJailConfigFileContent,
  updateJailConfigFile,
} from "../api/config";
import type { AddLogPathRequest } from "../types/config";

export interface UseJailConfigOperationsResult {
  addLogPath: (payload: AddLogPathRequest) => Promise<void>;
  deleteLogPath: (path: string) => Promise<void>;
  fetchRawContent: () => Promise<string>;
  saveRawContent: (content: string) => Promise<void>;
}

/**
 * Create callbacks for jail-specific config operations that are used by
 * jail config detail components.
 */
export function useJailConfigOperations(jailName: string): UseJailConfigOperationsResult {
  const addLog = useCallback(
    async (payload: AddLogPathRequest): Promise<void> => {
      await addLogPath(jailName, payload);
    },
    [jailName],
  );

  const deletePath = useCallback(
    async (path: string): Promise<void> => {
      await deleteLogPath(jailName, path);
    },
    [jailName],
  );

  const fetchRawContent = useCallback(async (): Promise<string> => {
    const result = await fetchJailConfigFileContent(`${jailName}.conf`);
    return result.content;
  }, [jailName]);

  const saveRawContent = useCallback(
    async (content: string): Promise<void> => {
      await updateJailConfigFile(`${jailName}.conf`, { content });
    },
    [jailName],
  );

  return {
    addLogPath: addLog,
    deleteLogPath: deletePath,
    fetchRawContent,
    saveRawContent,
  };
}
