import { useAuthStore } from '../store/auth'

export function setupAuthGuard(router) {
  router.beforeEach((to, from, next) => {
    const authStore = useAuthStore()
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

    // 检查路由是否需要认证
    if (requiresAuth) {
      // 如果需要认证且用户未登录
      if (!authStore.isAuthenticated) {
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
        return
      }

      // 如果需要特定角色
      const requiredRole = to.meta.role
      if (requiredRole && (!authStore.user || authStore.user.role !== requiredRole)) {
        next({ path: '/403' })
        return
      }
    }

    // 如果用户已登录但访问登录页
    if (authStore.isAuthenticated && (to.path === '/login' || to.path === '/register')) {
      next({ path: '/' })
      return
    }

    next()
  })
}
