import { useEffect } from 'react'
import { Navigate, Outlet } from 'react-router-dom'
import useAuthStore from '../../stores/authStore'

function AuthGuard() {
  const { user, fetchMe } = useAuthStore()

  useEffect(() => {
    if (user === null) {
      fetchMe()
    }
  }, [user, fetchMe])

  if (user === null) {
    return null
  }

  return user ? <Outlet /> : <Navigate to="/login" replace />
}

export default AuthGuard