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

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

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)
    }
    user.isLogin ? next() : next('/401')
    return
  }
  next()
})

export default router
