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

const appConfig = useAppConfig()

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

router.beforeEach(async (to, from, next) => {
  if (window.location.host === 'dasai.ezijing.com') {
    next()
  } else {
    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) {
        next('/401')
        return
      }
    }
    if (to.path === '/' && user.role?.id === 1 && appConfig.homeUrl) {
      next(appConfig.homeUrl)
      return
    }
    next()
  }
})

export default router
