import { LocalStorage } from '@assets/js-shop/LocalStorage';
import { ApolloError, DocumentNode, useQuery } from '@apollo/client';

const CACHE_QUERY = 'jsshop-persisted-query-';

export function usePersistedQuery<R>(key: string, query: DocumentNode, variables: object, ttlMinutes: number): {data: R, loading: boolean, error: ApolloError | null} {
   const cache = LocalStorage.get(CACHE_QUERY + key);
   const { loading, error, data } = useQuery(query, {
      skip: !!cache,
      variables
   });

   if (cache) {
      return { data: cache, loading: false, error: null };
   }

   if (loading || error) {
      return { data, loading, error };
   }

   LocalStorage.set(CACHE_QUERY + key, data, ttlMinutes);

   return { loading, data, error };

}
