import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import store from '@/store'
import routes from './routes'

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach(async (to, from) => {
  NProgress.start()
  if (to.name === 'login') {
    NProgress.done()
    return true
  }

  const { user, getCurrent } = store.getState('user')
  if (!user || !user.userId) {
    try {
      await getCurrent()
      NProgress.done()
    } catch (e) {
      NProgress.done()
      return { name: 'login', query: { from: encodeURIComponent(from.path) } }
    }
  }

  NProgress.done()
  return true
})

export default router;
