import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import WxCallback from '../views/wx_callback.vue'
import { isLoggedIn, clearTokens } from '../utils/auth'

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login, meta: { public: true } },
  { path: '/dashboard', component: Dashboard },
  { path: '/wx_callback', component: WxCallback, meta: { public: true } }
]

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

// 路由守卫：无效或缺失 token 时跳转登录
router.beforeEach((to, from, next) => {
  // 标记为 public 的路由直接放行
  if (to.meta && to.meta.public) return next()
  
  if (to.path === '/login') {
    // 已登录且未过期，访问登录页则跳转首页
    if (isLoggedIn()) {
      ElMessage.info('您已登录，正在跳转到首页...')
      return next('/dashboard')
    }
    return next()
  }
  
  // 其他受保护路由：检查登录状态
  if (!isLoggedIn()) {
    ElMessage.warning('请先登录')
    return next('/login')
  }
  
  return next()
})

export default router
