import { createContext, createElement, useCallback, useContext, useMemo, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";

const RefreshContext = createContext(null);

export function RefreshProvider({ children }) {
  const [refreshKey, setRefreshKey] = useState(0);
  const queryClient = useQueryClient();
  const refresh = useCallback(() => {
    setRefreshKey((current) => current + 1);
    queryClient.invalidateQueries();
  }, [queryClient]);
  const value = useMemo(() => ({ refresh, refreshKey }), [refresh, refreshKey]);

  return createElement(RefreshContext.Provider, { value }, children);
}

export function useRefreshSignal() {
  const context = useContext(RefreshContext);
  if (!context) {
    throw new Error("useRefreshSignal must be used inside RefreshProvider");
  }
  return context;
}

export function useRefreshKey() {
  return useRefreshSignal().refreshKey;
}
