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)
    }
    if (!user.isLogin) {
      next('/401')
      return
    }
  }
  if (!to.query.experiment_id) {
    next({
      path: to.path,
      query: {
        ...to.query,
        experiment_id: from.query.experiment_id || '7028276368903241728',
        student_id: from.query.student_id,
        force_tgc: from.query.force_tgc
      }
    })
  } else {
    next()
  }
})

export default router
