import { createContext, useContext, useEffect, useState } from 'react'
import { fetchWithRefresh } from '../../lib/api'

const AuthContext = createContext(null)

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
  fetchWithRefresh(`${import.meta.env.VITE_AUTH_SERVICE_URL}/auth/me`)
    .then(res => res.ok ? res.json() : null)
    .then(data => {
      if (data?.authenticated) {
        setUser(data)
      } else {
        setUser(null)
      }
    })
    .catch(() => setUser(null))
    .finally(() => setLoading(false))
}, [])

  const login = (userData) => setUser(userData)
  const logout = () => setUser(null)

  return (
    <AuthContext.Provider value={{ user, loading, login, logout }}>
      {children}
    </AuthContext.Provider>
  )
}

export const useAuth = () => useContext(AuthContext)
