import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(),
  routes: [{ path: '/:pathMatch(.*)*', redirect: '/course' }]
})

router.beforeEach(async (to, from, next) => {
  const whiteList = ['/401']
  const user = useUserStore()
  if (!user.isLogin && !whiteList.includes(to.path)) {
    try {
      await user.getUser()
    } catch (e) {
      console.error(e)
    }
    if (!user.isLogin) {
      location.href = `${import.meta.env.VITE_LOGIN_URL}?rd=${encodeURIComponent(location.href)}`
      return
    }
  }
  next()
})

export default router
