export default defineNuxtRouteMiddleware(async (to) => {
  if (process.server) {
    return
  }

  try {
    const user = await $fetch('/api/users/@me') as IUser

    if (!user._id) {
      throw createError({ statusCode: 500, statusMessage: 'No user was found' })
    }

    useState('user', () => user)

    if (to.meta.moderator && !user.role.moderator) {
      return navigateTo('/')
    }
  } catch (e) {
    console.error('Failed to get user', e)

    useState('user', () => null)

    return navigateTo('/login')
  }
})
