import { createRouter, createWebHistory } from 'vue-router'
import unifiedLoginSDK from 'oauth2-login-sdk';

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('../views/Dashboard.vue'),
    meta: {
      requiresAuth: true,
      title: '仪表板'
    }
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/Profile.vue'),
    meta: {
      requiresAuth: true,
      title: '个人中心'
    }
  },
  {
    path: '/oauth2/callback',
    name: 'callback',
    component: () => import('../views/Callback.vue'),
    meta: {
      title: '认证回调'
    }
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 路由守卫
router.beforeEach(async (to, _from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 统一登录Demo`;
  }

  // 检查是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  
  if (requiresAuth) {
    // 需要认证的路由
    if (!unifiedLoginSDK.isAuthenticated()) {
      try {
        console.log('🔒 用户未认证，正在跳转到登录页面...');
        await unifiedLoginSDK.login();
        // 登录会重定向到认证服务器，阻止当前路由切换
        next(false);
      } catch (error) {
        console.error('❌ 登录失败:', error);
        next(false);
      }
    } else {
      // 已认证，允许访问
      next();
    }
  } else if (unifiedLoginSDK.isCallback()) {
    // 处理OAuth2回调
    try {
      console.log('🔄 处理OAuth2回调...');
      await unifiedLoginSDK.handleCallback();
      // 回调处理完成后SDK会自动跳转到homePage
    } catch (error) {
      console.error('❌ 回调处理失败:', error);
      next('/');
    }
  } else {
    // 公开路由
    next();
  }
});

// 路由后置守卫
router.afterEach((to, from) => {
  console.log(`🧭 路由切换: ${from.path} -> ${to.path}`);
});

export default router