/**
 * React hook for loading filter config metadata used by the filter tab.
 */
import { useCallback } from "react";
import { fetchFilters, createFilter, assignFilterToJail } from "../api/config";
import { useListData } from "./useListData";
import type { FilterConfig, FilterCreateRequest, FilterListResponse } from "../types/config";

export interface UseFilterListResult {
  filters: FilterConfig[];
  loading: boolean;
  error: string | null;
  refresh: () => void;
  createFilter: (payload: FilterCreateRequest) => Promise<FilterConfig>;
  assignFilterToJail: (jailName: string, payload: { filter_name: string }, reload: boolean) => Promise<void>;
}

/**
 * Load the filter inventory and expose refresh semantics.
 */
export function useFilterList(): UseFilterListResult {
  const fetcher = useCallback(
    (signal: AbortSignal) => fetchFilters(signal),
    [],
  );

  const selector = useCallback((response: FilterListResponse) => response.filters, []);

  const { items: filters, loading, error, refresh } = useListData<FilterListResponse, FilterConfig>({
    fetcher,
    selector,
    errorMessage: "Failed to load filters",
  });

  const handleCreateFilter = useCallback(
    async (payload: FilterCreateRequest): Promise<FilterConfig> => {
      return await createFilter(payload);
    },
    [],
  );

  const handleAssignFilterToJail = useCallback(
    async (jailName: string, payload: { filter_name: string }, reload: boolean): Promise<void> => {
      await assignFilterToJail(jailName, payload, reload);
    },
    [],
  );

  return {
    filters,
    loading,
    error,
    refresh,
    createFilter: handleCreateFilter,
    assignFilterToJail: handleAssignFilterToJail,
  };
}
