"use client";

import { useQuery } from "@tanstack/react-query";

import { getGlobalSearch } from "../service/search-service";
import { useDebouncedValue } from "./use-debounced-value";

// Nothing is searched until the reader has typed at least this much.
const MIN_QUERY_LENGTH = 2;
const SEARCH_STALE_TIME_MS = 30 * 1000;

export function useGlobalSearch(query: string) {
  const debouncedQuery = useDebouncedValue(query.trim(), 300);
  const isEnabled = debouncedQuery.length >= MIN_QUERY_LENGTH;

  const search = useQuery({
    queryKey: ["global-search", debouncedQuery],
    queryFn: () => getGlobalSearch(debouncedQuery),
    enabled: isEnabled,
    staleTime: SEARCH_STALE_TIME_MS,
  });

  return {
    results: search.data?.results ?? [],
    // True while the reader has typed enough and the answer is on its way.
    isLoading: isEnabled && search.isLoading,
    isEnabled,
    error:
      search.error instanceof Error
        ? search.error.message
        : search.error
          ? "Unable to search."
          : null,
  };
}
