"use client";

import { filterSelectItems } from "@/components/FormElements/select";
import type { ILabelValue } from "@/types/shared";
import { useCallback } from "react";

/**
 * Example factory for `Select` server search — wire your API inside `fetchItems`.
 *
 * @example
 * const searchCountries = useSelectSearchQuery({
 *   queryKey: ["countries", "select-search"],
 *   fetchItems: async (q) => {
 *     const res = await api.get("/countries", { params: { q } });
 *     return res.data.map((c) => ({ label: c.name, value: c.code }));
 *   },
 *   fallbackItems: Countries,
 * });
 *
 * <Select searchable searchMode="server" searchQueryKey={["countries"]} searchFn={searchCountries} items={Countries} ... />
 */
export function useSelectSearchQuery({
  fetchItems,
  fallbackItems = [],
}: {
  fetchItems: (query: string) => Promise<ILabelValue[]>;
  /** Used when the API is unavailable or for local dev until the endpoint exists. */
  fallbackItems?: readonly ILabelValue[];
}) {
  return useCallback(
    async (query: string) => {
      try {
        return await fetchItems(query);
      } catch {
        return filterSelectItems(fallbackItems, query);
      }
    },
    [fetchItems, fallbackItems],
  );
}
