import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  { path: '/', name: 'index', component: () => import('@/views/index/index.vue') },
  { path: '/chat', name: 'Chat', component: () => import('@/views/wxPage/ChatEdit.vue'), meta: { requiresAuth: false } },
  { path: '/balance', name: 'Balance', component: () => import('@/views/wxPage/BalanceEdit.vue'), meta: { requiresAuth: false } },
  { path: '/works', name: 'Works', component: () => import('@/views/work/works.vue'), meta: { requiresAuth: true } },
  { path: '/about', name: 'About', component: () => import('@/views/About.vue') },
  { path: '/profile', name: 'Profile', component: () => import('@/views/Profile.vue'), meta: { requiresAuth: true } },
  { path: '/article', name: 'Article', component: () => import('@/views/article/list.vue') },
  { path: '/article-detail', name: 'ArticleDetail', component: () => import('@/views/article/detail.vue') },
  { path: '/gongzidan', name: 'GongZiDan', component: () => import('@/views/other/gongzidan.vue') },
]

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

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  const userStore = useUserStore()

  // 如果有 token 但还没验证过，无论是进哪个页面，都静默验证一下以恢复全局状态
  if (token && !userStore.tokenChecked) {
    try {
      await userStore.fetchProfile()
      if (!userStore.tokenValid) {
        localStorage.removeItem('token')
      }
    } catch {
      localStorage.removeItem('token')
      userStore.reset()
    }
  }

  // 不需要认证的页面，直接放行
  if (!to.meta.requiresAuth) return next()

  // 需要认证的页面：如果没有 token 或者 token 已失效，跳回首页并唤起登录框
  if (!token || !userStore.tokenValid) {
    return next({ path: '/', query: { showLogin: 1 } })
  }

  next()
})

export default router
