import NProgress from 'nprogress' // progress bar
import type { LocationQueryRaw, Router } from 'vue-router'

import { useUserStore } from '@/store'
import { isLogin } from '@/utils/auth'

// 不需要登录验证的路由名称
const whiteList = ['login', 'home']

export default function setupUserLoginInfoGuard(router: Router) {
  router.beforeEach(async (to) => {
    NProgress.start()
    const userStore = useUserStore()
    if (isLogin()) {
      if (userStore.role) {
        return true
      } else {
        try {
          await userStore.info()
          return true
        } catch (error) {
          await userStore.logout()
          return {
            name: 'login',
            query: {
              redirect: to.name,
              ...to.query,
            } as LocationQueryRaw,
          }
        }
      }
    } else {
      // 在白名单中的路由不需要登录验证
      if (whiteList.includes(to.name as string)) {
        return true
      }
      return {
        name: 'login',
        query: {
          redirect: to.name,
          ...to.query,
        } as LocationQueryRaw,
      }
    }
  })
}
