/**
 * React hook for loading action metadata used by the actions tab.
 */
import { useCallback } from "react";
import { fetchActions, removeActionFromJail, createAction, assignActionToJail } from "../api/config";
import { useListData } from "./useListData";
import type { ActionConfig, ActionCreateRequest, ActionListResponse } from "../types/config";

export interface UseActionListResult {
  actions: ActionConfig[];
  loading: boolean;
  error: string | null;
  refresh: () => void;
  removeActionFromJail: (jailName: string, actionName: string) => Promise<void>;
  createAction: (payload: ActionCreateRequest) => Promise<ActionConfig>;
  assignActionToJail: (jailName: string, payload: { action_name: string }, reload: boolean) => Promise<void>;
}

/**
 * Load the action inventory and expose related action operations.
 */
export function useActionList(): UseActionListResult {
  const fetcher = useCallback(
    (signal: AbortSignal) => fetchActions(signal),
    [],
  );

  const selector = useCallback((response: ActionListResponse) => response.actions, []);

  const { items: actions, loading, error, refresh } = useListData<ActionListResponse, ActionConfig>({
    fetcher,
    selector,
    errorMessage: "Failed to load actions",
  });

  const handleRemoveActionFromJail = useCallback(
    async (jailName: string, actionName: string): Promise<void> => {
      await removeActionFromJail(jailName, actionName);
    },
    [],
  );

  const handleCreateAction = useCallback(
    async (payload: ActionCreateRequest): Promise<ActionConfig> => {
      return await createAction(payload);
    },
    [],
  );

  const handleAssignActionToJail = useCallback(
    async (jailName: string, payload: { action_name: string }, reload: boolean): Promise<void> => {
      await assignActionToJail(jailName, payload, reload);
    },
    [],
  );

  return {
    actions,
    loading,
    error,
    refresh,
    removeActionFromJail: handleRemoveActionFromJail,
    createAction: handleCreateAction,
    assignActionToJail: handleAssignActionToJail,
  };
}
