"use client";

import { QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { useState } from "react";
import { useAuthStore } from "@/store/authStore";
import { createAppQueryClient } from "./mutationStaleness";

export function QueryProvider({ children }: { children: React.ReactNode }) {
  const accountId = useAuthStore(s => s.user?.id ?? "public");
  return <AccountQueryProvider key={accountId}>{children}</AccountQueryProvider>;
}

/** Account switches remount the query scope before another account can read its cache. */
function AccountQueryProvider({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      createAppQueryClient({
        defaultOptions: {
          queries: {
            staleTime: 60 * 1000, // 1 minute
            gcTime: 5 * 60 * 1000, // 5 minutes
            retry: 1,
            refetchOnWindowFocus: false,
          },
          mutations: {
            retry: 0,
          },
        },
      })
  );

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      {process.env.NODE_ENV === "development" && (
        <ReactQueryDevtools initialIsOpen={false} />
      )}
    </QueryClientProvider>
  );
}
