'use client'

import { IApiErrorRepsonse } from '@/types/error.types'
import { QueryClient, QueryClientProvider, HydrationBoundary, QueryCache } from '@tanstack/react-query'
import { ReactNode, useState } from 'react'
import { removeToken } from './func'
import { useSharedStore } from '@/shared/store/sharedStore'

export default function QueryProvider({ children }: { children: ReactNode }) {
  const { setIsLogin } = useSharedStore()
  const [client] = useState(() => new QueryClient({
    queryCache: new QueryCache({
      onError: async (error: IApiErrorRepsonse) => {
        if (error.response?.status === 401) {
          removeToken()
          setIsLogin(false)
        }
      }
    }),
    defaultOptions: {
      queries: {
        staleTime: 1000 * 60 * 5, // داده‌ها برای 5 دقیقه معتبر هستند

      }
    }
  }))

  return (
    <QueryClientProvider client={client}>
      <HydrationBoundary state={{}}>
        {children}
      </HydrationBoundary>
    </QueryClientProvider>
  )
}