import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { searchApi } from '../apis';
import { searchKeys } from '../keys';
import { SEARCH_GC_TIME, SEARCH_RESULTS_STALE_TIME } from '../constants';
import type { NurseSearchFilters } from '../types';

/**
 * The C2 discovery query. **The filter object is the query key** (`searchKeys.results`), so an
 * identical filter set is served straight from cache — changing a filter and reverting to a previous
 * set is a cache hit with zero network calls. `placeholderData: keepPreviousData` keeps the previous
 * page/results on screen while a new filter loads, so the list never flashes empty. Enabled only once
 * the two required facets (category + city) are chosen.
 */
export function useNurseSearch(filters: NurseSearchFilters) {
  return useQuery({
    queryKey: searchKeys.results(filters),
    queryFn: () => searchApi.searchNurses(filters),
    enabled: filters.serviceCategoryId > 0 && filters.cityId > 0,
    staleTime: SEARCH_RESULTS_STALE_TIME,
    gcTime: SEARCH_GC_TIME,
    placeholderData: keepPreviousData,
  });
}
