/**
 * React Query Provider
 * Simple provider setup for TanStack Query with CSP nonce support
 */

"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { useState } from "react";
import { isApiError } from "@/lib/api/runtime/client";

interface QueryProviderProps {
  children: React.ReactNode;
  nonce?: string;
}

export function QueryProvider({ children }: QueryProviderProps) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 5 * 60 * 1000, // 5 minutes
            gcTime: 10 * 60 * 1000, // 10 minutes
            refetchOnWindowFocus: false, // Prevent excessive refetches in development
            refetchOnMount: true, // Only refetch if data is stale (>5 min old)
            refetchOnReconnect: true, // Only refetch on reconnect if stale
            retry: (failureCount, error: unknown) => {
              if (isApiError(error)) {
                const status = error.response?.status;
                // Don't retry on 4xx errors (client errors)
                if (status && status >= 400 && status < 500) {
                  return false;
                }
                const body = error.body as Record<string, unknown> | undefined;
                const code = typeof body?.code === "string" ? body.code : undefined;
                // Don't retry on auth errors or rate limits
                if (code === "AUTHENTICATION_REQUIRED" || code === "FORBIDDEN") {
                  return false;
                }
              }
              return failureCount < 3;
            },
            retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000), // Exponential backoff
          },
        },
      })
  );

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