/**
 * React hook for loading and updating a single parsed filter config.
 */

import { useCallback } from "react";
import { useConfigItem } from "./useConfigItem";
import { fetchParsedFilter, updateParsedFilter } from "../api/config";
import type { FilterConfig, FilterConfigUpdate } from "../types/config";

export interface UseFilterConfigResult {
  config: FilterConfig | null;
  loading: boolean;
  error: string | null;
  saving: boolean;
  saveError: string | null;
  refresh: () => void;
  save: (update: FilterConfigUpdate) => Promise<void>;
}

/**
 * Load one filter config by name and expose a ``save`` callback for partial
 * updates.
 *
 * @param name - Filter base name (e.g. ``"sshd"``).
 */
export function useFilterConfig(name: string): UseFilterConfigResult {
  const fetchFn = useCallback(
    (signal: AbortSignal) => fetchParsedFilter(name, signal),
    [name],
  );
  const saveFn = useCallback(
    (update: FilterConfigUpdate) => updateParsedFilter(name, update),
    [name],
  );

  const { data, loading, error, saving, saveError, refresh, save } = useConfigItem<
    FilterConfig,
    FilterConfigUpdate
  >({
    fetchFn,
    saveFn,
    mergeOnSave: (prev, update) =>
      prev
        ? {
            ...prev,
            ...Object.fromEntries(Object.entries(update).filter(([, v]) => v != null)),
          }
        : prev,
  });

  return {
    config: data,
    loading,
    error,
    saving,
    saveError,
    refresh,
    save,
  };
}
