import { get, set, del } from "idb-keyval";
import { QueryClient } from "@tanstack/react-query";
import { persistQueryClient } from "@tanstack/react-query-persist-client";
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";

export const CACHE_KEY = "khollise-cache"; // Key for IndexedDB storage

// Check if we're in a browser environment with IndexedDB support
const isIndexedDBAvailable = () => {
  return (
    typeof window !== "undefined" &&
    typeof window.indexedDB !== "undefined" &&
    window.indexedDB !== null
  );
};

// Create QueryClient with persistence
const createQueryClient = () => {
  const queryClient = new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 1000 * 60 * 5, // 5 minutes
        gcTime: 1000 * 60 * 60 * 24, // 24 hours (formerly cacheTime)
        refetchOnWindowFocus: false,
        retry: 2,
      },
    },
  });

  // Only set up persistence if IndexedDB is available
  if (isIndexedDBAvailable()) {
    persistQueryClient({
      queryClient,
      persister: createAsyncStoragePersister({
        storage: { getItem: get, setItem: set, removeItem: del },
        key: CACHE_KEY,
      }),
      maxAge: 1000 * 60 * 60 * 24, // 24 hours
      buster: "v1", // Change this to invalidate cache
    });
  } else {
    console.warn("Cache persistence disabled - IndexedDB not available");
  }

  return queryClient;
};

const queryClient = createQueryClient();
export default queryClient;
