import chadApi from '#shared/chad-api'

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

  if (!me.value) {
    try {
      setMe(await chadApi('/me', { method: 'GET' }))

      if (to.meta.auth !== false)
        return navigateTo({ name: 'Index' })
    }
    catch {
      if (to.meta.auth !== 'guest') {
        return navigateTo({ name: 'Login' })
      }
    }
  }

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