"use client";

import { ApiError } from "@/lib/api/create-api-client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactNode, useState } from "react";

interface Props {
  children: ReactNode;
}

export default function ReactQueryProvider({ children }: Props) {
  // Use useState to ensure QueryClient is only created once per component lifecycle
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            // Custom retry logic - don't retry for specific error codes
            retry: (failureCount, error) => {
              // Don't retry for 429 (rate limit) or 401 (unauthorized)
              if (error instanceof ApiError) {
                if (error.status === 429 || error.status === 401) {
                  return false;
                }
              }
              // Default: retry up to 3 times for other errors
              return failureCount < 3;
            },
            // Cache data for 30 seconds by default
            staleTime: 30 * 1000,
          },
          mutations: {
            // Don't retry mutations by default
            retry: false,
          },
        },
      }),
  );

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