import { keepPreviousData, useInfiniteQuery } from "@tanstack/react-query";

import { api } from "../client";
import { HttpError } from "../errors";
import { keys } from "../query-keys";

const SEARCH_PAGE = 20;

export function useSearch(q: string, visibility: string | null) {
  const term = q.trim();

  return useInfiniteQuery({
    queryKey: keys.searchResults(term, visibility),
    enabled: term.length > 0,
    initialPageParam: 0,
    queryFn: async ({ pageParam }) => {
      const { data, error, response } = await api.GET("/api/admin/search", {
        params: {
          query: {
            q: term,
            ...(visibility ? { visibility } : {}),
            offset: pageParam,
            limit: SEARCH_PAGE,
          },
        },
      });

      if (error || !data) throw new HttpError(response.status);

      return data;
    },
    placeholderData: keepPreviousData,
    getNextPageParam: (lastPage, allPages) => {
      const loaded = allPages.reduce((n, page) => n + page.hits.length, 0);

      return loaded < lastPage.estimated_total ? loaded : undefined;
    },
  });
}
