import chadApi from '#shared/chad-api'

export default defineNuxtRouteMiddleware(async (to, from) => {
  const { me, setMe } = useAuth()

  if (!me.value && !from?.name) {
    try {
      setMe(await chadApi('/me'))
    }
    catch {
      if (to.meta.auth !== 'guest') {
        return navigateTo({ name: 'Login' })
      }
    }
  }

  if (me.value && to.meta.auth === 'guest') {
    return navigateTo('/')
  }
})
