"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState } from "react";
import {
  getRestaurantSlugFromPath,
  restorePersistedRestaurantQueries,
} from "@/lib/helpers/themeCache";

function createQueryClient() {
  const client = new QueryClient({
    defaultOptions: {
      queries: {
        retry: false,
        retryOnMount: false,
      },
      mutations: {
        retry: false,
      },
    },
  });

  if (typeof window !== "undefined") {
    const slug = getRestaurantSlugFromPath();
    if (slug) {
      restorePersistedRestaurantQueries(client, slug);
    }
  }

  return client;
}

export function ReactQueryProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [queryClient] = useState(createQueryClient);

  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
}
