import { createRouter, createWebHistory } from 'vue-router'
import LoginPage from '../views/LoginPage.vue'
import RegisterPage from '../views/RegisterPage.vue'
import HallPage from '../views/HallPage.vue'
import ChengduGamePage from '../views/ChengduGamePage.vue'
import { readStoredAuth } from '../utils/auth-storage'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/hall',
    },
    {
      path: '/login',
      name: 'login',
      component: LoginPage,
      meta: { guestOnly: true },
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterPage,
      meta: { guestOnly: true },
    },
    {
      path: '/hall',
      name: 'hall',
      component: HallPage,
      meta: { requiresAuth: true },
    },
    {
      path: '/game/chengdu/:roomId?',
      name: 'chengdu-game',
      component: ChengduGamePage,
      meta: { requiresAuth: true },
    },
  ],
})

router.beforeEach((to) => {
  const auth = readStoredAuth()
  const isAuthed = Boolean(auth)

  if (to.meta.requiresAuth && !isAuthed) {
    return { path: '/login', query: { redirect: to.fullPath } }
  }

  if (to.meta.guestOnly && isAuthed) {
    return { path: '/hall' }
  }

  return true
})

export default router
