import { useCallback, useId } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";

export function useAdminQuery(queryFn, options = {}) {
  const defaultQueryId = useId();

  const {
    enabled = true,
    errorMessage = "请求失败",
    keepPreviousData = false,
    initialData = null,
    queryKey = ["admin-query", defaultQueryId],
    refetchInterval,
    staleTime
  } = options;
  const queryClient = useQueryClient();
  const query = useQuery({
    enabled,
    placeholderData: keepPreviousData ? (previousData) => previousData ?? initialData : initialData,
    queryFn,
    queryKey,
    refetchInterval,
    staleTime
  });

  const reload = useCallback(async () => {
    const result = await query.refetch();
    return result.data ?? null;
  }, [query]);

  const setData = useCallback(
    (updater) => {
      queryClient.setQueryData(queryKey, updater);
    },
    [queryClient, queryKey]
  );

  const error = query.error ? query.error.message || errorMessage : "";

  return {
    data: query.data,
    error,
    loading: query.isLoading || query.isFetching,
    reload,
    setData
  };
}
