/**
 * React hook for loading and mutating a single jail configuration.
 */

import { useCallback, useEffect, useRef, useState } from "react";
import { addLogPath, fetchJailConfig, updateJailConfig } from "../api/config";
import { handleFetchError } from "../utils/fetchError";
import type { AddLogPathRequest, JailConfig, JailConfigUpdate } from "../types/config";

export interface UseJailConfigDetailResult {
  jail: JailConfig | null;
  loading: boolean;
  error: string | null;
  refresh: () => void;
  updateJail: (update: JailConfigUpdate) => Promise<void>;
  addLog: (req: AddLogPathRequest) => Promise<void>;
}

/**
 * Load the detail view for a single jail config and expose edit actions.
 */
export function useJailConfigDetail(name: string): UseJailConfigDetailResult {
  const [jail, setJail] = useState<JailConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const abortRef = useRef<AbortController | null>(null);

  const load = useCallback((): void => {
    abortRef.current?.abort();
    const ctrl = new AbortController();
    abortRef.current = ctrl;
    setLoading(true);
    setError(null);

    fetchJailConfig(name)
      .then((resp) => {
        if (!ctrl.signal.aborted) {
          setJail(resp.jail);
        }
      })
      .catch((err: unknown) => {
        if (!ctrl.signal.aborted) {
          handleFetchError(err, setError, "Failed to fetch jail config");
        }
      })
      .finally(() => {
        if (!abortRef.current?.signal.aborted) {
          setLoading(false);
        }
      });
  }, [name]);

  useEffect(() => {
    load();
    return (): void => {
      abortRef.current?.abort();
    };
  }, [load]);

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

  const addLog = useCallback(
    async (req: AddLogPathRequest): Promise<void> => {
      await addLogPath(name, req);
      load();
    },
    [name, load],
  );

  return { jail, loading, error, refresh: load, updateJail, addLog };
}
