import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import DashboardView from '../views/DashboardView.vue'
import AiView from '../views/AiView.vue'
import LoginView from '../views/LoginView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'dashboard',
      component: DashboardView,
      meta: { requiresAuth: true }
    },
    {
      path: '/ai',
      name: 'ai',
      component: AiView,
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { guest: true }
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const isLoggedIn = userStore.checkLoginStatus()

  // 需要登录的页面
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/login')
    return
  }

  // 游客页面（如登录页），已登录用户自动跳转
  if (to.meta.guest && isLoggedIn) {
    next('/')
    return
  }

  next()
})

export default router
