import { useQuery, useQueryClient } from '@tanstack/react-query';

export const useGlobal = <T>(key: string | string[], initialData: T | (() => T)) => {
  const queryClient = useQueryClient();

  const theKey = Array.isArray(key) ? ['USE_GLOBAL', ...key] : ['USE_GLOBAL', key];
  const theInitialData = typeof initialData === 'function' ? (initialData as () => T)() : initialData;

  const { data } = useQuery<T>({
    queryKey: theKey,
    enabled: false,
    queryFn: () => theInitialData,
    initialData: theInitialData,
    staleTime: Infinity,
  });

  const setData: React.Dispatch<React.SetStateAction<T>> = (arg) => {
    const val = typeof arg === 'function' ? (arg as (arg0: T) => T)(data as T) : arg;
    queryClient.setQueryData(theKey, () => val);
  };

  const reset = () => {
    queryClient.removeQueries({ queryKey: theKey });
  };

  const refresh = () => {
    queryClient.invalidateQueries({ queryKey: theKey });
  };

  return [data!, setData, refresh, reset] as const;
};
