import router from '@/router'
import NProgress from 'nprogress'
import { useUserStore } from '@/stores/modules/user'

NProgress.configure({ showSpinner: false })

const WHITE_LIST = ['/login', '/404']

router.beforeEach(async (to, _from, next) => {
  NProgress.start()
  document.title = (to.meta.title as string) || '零食商城管理后台'

  const userStore = useUserStore()

  // 白名单（login/404）
  if (WHITE_LIST.includes(to.path)) {
    if (to.path === '/login' && userStore.isLoggedIn) {
      next('/')
    } else {
      next()
    }
    return
  }

  // 未登录 → 跳登录
  if (!userStore.isLoggedIn) {
    next(`/login?redirect=${encodeURIComponent(to.path)}`)
    NProgress.done()
    return
  }

  // 已登录但未拉取过管理员信息 → 拉取一次
  if (!userStore.adminInfo) {
    try {
      await userStore.fetchAdminInfo()
    } catch (err) {
      userStore.clearAuth()
      next(`/login?redirect=${encodeURIComponent(to.path)}`)
      NProgress.done()
      return
    }
  }

  next()
})

router.afterEach(() => {
  NProgress.done()
})
