// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import { routes } from './routes'
import { useUserStoreWithOut } from '@/stores/modules/user'

// 创建 Router 实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStoreWithOut()
  const token = userStore.access_token
  const pushRecordId = userStore.pushRecordId

  if (to.meta.requiresAuth && !token && !pushRecordId) {
    // 未登录时跳转登录页
    next({
      path: '/login',
    })
  } else {
    next()
  }
  if (to.meta && to.meta.title) {
    document.title = to.meta.title as string
  } else {
    // 可设置默认标题
    document.title = '默认标题'
  }
})

// 可选：设置页面标题
router.afterEach((to) => {
  if (to.meta.title) {
    document.title = to.meta.title as string
  }
})

export default router
