'use client'

import { useSession } from 'next-auth/react'
import { useEffect } from 'react'
import useUserStore from '../store/userStore'

export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const { data: session } = useSession()
  const { setUser, setAuthenticated } = useUserStore()

  useEffect(() => {
    const fetchUserData = async () => {
      if (!session?.accessToken) {
        setUser(null)
        setAuthenticated(false)
        return
      }
 
      const base = process.env.NEXT_PUBLIC_API_URL || '/api/v1'
      const baseClean = base.replace(/\/+$/, '')
      const url = `${baseClean}/account/user/`
      console.log('[AuthProvider] Fetching user from:', url)

      try {
        const response = await fetch(url, {
          headers: {
            Authorization: `Bearer ${session.accessToken}`,
            Accept: 'application/json',
          },
          cache: 'no-store',
          redirect: 'follow',
        })

        if (!response.ok) {
          const errorText = await response.text()
          console.error('Error fetching user data:', {
            status: response.status,
            url: url,
            body: errorText,
          })
          throw new Error(`Error fetching user data: ${response.status} ${errorText}`)
        }

        const userData = await response.json()

        setUser({
          id: userData.id,
          name: userData.name || session.user.name || '',
          surname: userData.surname || '',
          email: userData.email || session.user.email || '',
          image: userData.imageURL || userData.image,
          account_type: userData.account_type,
          login: userData.login ?? session.user.name ?? '',
          uuid: userData.uuid,
        })
        setAuthenticated(true)
      } catch (error) {
        console.error('Error in fetchUserData:', error)
        setAuthenticated(false)
        setUser(null)
      }
    }

    fetchUserData()
  }, [session, setUser, setAuthenticated])

  return <>{children}</>
}
