const LOGIN_PATH = '/login'

export default defineNuxtRouteMiddleware(async (to) => {
  if (to.path === LOGIN_PATH) return
  const { user, refresh } = useUser()
  if (!user.value) await refresh()
  if (user.value) return
  const redirect = to.fullPath.startsWith('/') ? to.fullPath : `/${to.fullPath}`
  return navigateTo({ path: LOGIN_PATH, query: { redirect } }, { replace: true })
})
