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

export const useGlobalQueryString = () => {
  const queryClient = useQueryClient();
  const [queryString, setQueryString] = useState<string>('');

  useEffect(() => {
    const updateQueryString = () => {
      const globalCache = queryClient
        .getQueryCache()
        .getAll()
        .filter((cache) => cache.queryKey[1] === 'QUERY_STATE')
        .map((cache) => ({
          key: cache.queryKey[2] as string,
          data: cache.state.data as string | number | null,
        }));

      const globalParams = globalCache.filter((cache) => cache.data !== null);

      const searchParams = new URLSearchParams();
      globalParams.forEach((cache) => {
        if (cache.data !== null) {
          searchParams.append(cache.key, cache.data.toString());
        }
      });
      setQueryString(searchParams.toString());
    };

    updateQueryString();

    const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
      if (event.query.queryKey[1] === 'QUERY_STATE') {
        updateQueryString();
      }
    });

    return unsubscribe;
  }, [queryClient]);

  return queryString;
};
