'use client'

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

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

  return (
    <QueryClientProvider client={client}>
      <HydrationBoundary state={null}>
        {children}
      </HydrationBoundary>
      <ReactQueryDevtools
        initialIsOpen={false}
        buttonPosition="bottom-left"
      />
    </QueryClientProvider>
  )
}