import router, { resetRouter } from '@/router'
import { WHITE_LIST, LOGIN_URL } from '@/constants'
import { useAuthStore, useUserStore } from '@/stores'
import { useNProgress } from '@/utils/nprogress'
import { initDynamicRouter } from '@/router/modules/dynamicRouter'

const { start, done } = useNProgress()
export const setupAuthRoutes = () => {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const authStore = useAuthStore()

    start()

    if (to.path.toLocaleLowerCase() === LOGIN_URL) {
      if (userStore.token) return next(from.fullPath)
      resetRouter()
      return next()
    }
    if (WHITE_LIST.includes(to.path)) return next()

    if (!userStore.token) return next({ path: LOGIN_URL, replace: true })

    if (!authStore.getMenuList.length) {
      await initDynamicRouter()
      return next({ ...to, replace: true })
    }
    authStore.setRouteName(to.name as string)
    next()
  })
  router.afterEach(() => {
    done() // 结束Progress
  })
}
