import { QueryClient } from '@tanstack/react-query'
import { ApiError } from 'src/lib/api-context'
import { queryPersister } from 'src/lib/query-persister'

// Singleton QueryClient — module-level so queryFns and other non-hook
// callers can reach it (e.g. opportunistic `setQueryData` writes from
// inside a fetch). The provider in `_layout.tsx` mounts this same
// instance, so React hook callers (`useQuery`, `useQueryClient`) and
// imperative callers see one cache.
export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      gcTime: 1000 * 60 * 30,
      persister: queryPersister.persisterFn,
      retry: (failureCount, error) => {
        if (error instanceof ApiError && error.status < 500) return false
        return failureCount < 2
      },
    },
  },
})
