/**
 * 路由守卫使用示例
 */

import { RouterGuard, RouterGuardOptions } from './router';
import { Auth } from '../core/auth';
import { Storage } from '../utils/storage';

// 基础使用示例
export function basicUsageExample() {
  // 创建存储实例
  const storage = new Storage('localStorage');
  
  // 创建认证实例
  const auth = new Auth(storage);
  
  // 初始化认证配置
  auth.init({
    clientId: 'your-client-id',
    basepath: 'https://api.example.com',
    homePage: '/dashboard',
    idpLogoutUrl: 'https://idp.example.com/logout'
  } as any);
  
  // 创建路由守卫
  const routerGuard = new RouterGuard(auth);
  
  return routerGuard;
}

// Vue路由配置示例
export function vueRouterConfigExample() {
  // 在Vue项目中的路由配置
  const routes = [
    {
      path: '/',
      name: 'Home',
      component: 'HomeView', // 示例组件名
      meta: {
        auth: {
          requiresAuth: false // 首页不需要认证
        }
      }
    },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: 'DashboardView', // 示例组件名
      meta: {
        auth: {
          requiresAuth: true, // 需要登录
          redirectUri: '/login' // 登录页面
        }
      }
    },
    {
      path: '/admin',
      name: 'Admin',
      component: 'AdminView', // 示例组件名
      meta: {
        auth: {
          requiresAuth: true,
          requiredPermissions: ['admin:access'], // 需要管理员权限
          unauthorizedRedirectUri: '/unauthorized' // 权限不足跳转页面
        }
      }
    },
    {
      path: '/user-management',
      name: 'UserManagement',
      component: 'UserManagementView', // 示例组件名
      meta: {
        auth: {
          requiresAuth: true,
          requiredPermissions: ['user:read', 'user:write'], // 需要多个权限
          requireAllPermissions: true, // 需要所有权限
          requiredRoles: ['admin'], // 需要管理员角色
          requireAllRoles: true // 需要所有角色
        }
      }
    },
    {
      path: '/profile',
      name: 'Profile',
      component: 'ProfileView', // 示例组件名
      meta: {
        auth: {
          requiresAuth: true,
          requiredPermissions: ['profile:view', 'profile:edit'], // 多个权限
          requireAllPermissions: false // 任一权限即可
        }
      }
    }
  ];

  return routes;
}

// Vue路由守卫集成示例
export function vueRouterIntegrationExample() {
  // 创建路由守卫实例
  const storage = new Storage('localStorage');
  const auth = new Auth(storage);
  const routerGuard = new RouterGuard(auth);

  // Vue Router 3.x 配置
  const routerConfigV3 = {
    routes: vueRouterConfigExample(),
    beforeEach: routerGuard.createVueGuard()
  };

  // Vue Router 4.x 配置
  const routerConfigV4 = {
    routes: vueRouterConfigExample(),
    beforeEnter: routerGuard.createVueGuard()
  };

  return { routerConfigV3, routerConfigV4 };
}

// 手动权限检查示例
export async function manualPermissionCheckExample(routerGuard: RouterGuard) {
  try {
    // 检查单个权限
    const hasReadPermission = await routerGuard.hasPermission('user:read');
    console.log('Has read permission:', hasReadPermission);

    // 检查多个权限（需要全部）
    const hasAllPermissions = await routerGuard.hasPermission(
      ['user:read', 'user:write'], 
      true
    );
    console.log('Has all permissions:', hasAllPermissions);

    // 检查多个权限（需要任一）
    const hasAnyPermission = await routerGuard.hasPermission(
      ['user:read', 'admin:access'], 
      false
    );
    console.log('Has any permission:', hasAnyPermission);

    // 检查角色
    const hasAdminRole = await routerGuard.hasRole('admin');
    console.log('Has admin role:', hasAdminRole);

    // 获取当前用户
    const currentUser = routerGuard.getCurrentUser();
    console.log('Current user:', currentUser);

  } catch (error) {
    console.error('Permission check failed:', error);
  }
}

// 高级配置示例
export function advancedConfigurationExample() {
  const storage = new Storage('localStorage');
  const auth = new Auth(storage);
  const routerGuard = new RouterGuard(auth);

  // 自定义路由守卫选项
  const customGuardOptions: RouterGuardOptions = {
    requiresAuth: true,
    requiredPermissions: ['custom:permission'],
    requiredRoles: ['custom:role'],
    requireAllPermissions: true,
    requireAllRoles: false,
    redirectUri: '/custom-login',
    unauthorizedRedirectUri: '/custom-forbidden'
  };

  return { routerGuard, customGuardOptions };
}

// 错误处理示例
export async function errorHandlingExample(routerGuard: RouterGuard) {
  try {
    // 执行权限检查
    const result = await routerGuard.check({
      requiresAuth: true,
      requiredPermissions: ['some:permission']
    });

    if (!result.allowed) {
      switch (result.reason) {
        case 'NOT_AUTHENTICATED':
          console.log('用户未认证，将跳转到登录页');
          break;
        case 'INSUFFICIENT_PERMISSIONS':
          console.log('权限不足:', result.details);
          break;
        case 'INSUFFICIENT_ROLES':
          console.log('角色不足:', result.details);
          break;
        default:
          console.log('访问被拒绝');
      }
    }
  } catch (error) {
    console.error('路由守卫检查出错:', error);
  }
}

// 实际应用示例 - 完整的Vue组件集成
export class SecureRouteManager {
  private routerGuard: RouterGuard;
  private auth: Auth;

  constructor() {
    const storage = new Storage('localStorage');
    this.auth = new Auth(storage);
    this.routerGuard = new RouterGuard(this.auth);
  }

  // 初始化SDK
  initializeSDK(config: any) {
    this.auth.init(config);
  }

  // 获取Vue路由守卫
  getVueRouterGuard() {
    return this.routerGuard.createVueGuard();
  }

  // 手动检查路由权限
  async checkRouteAccess(routeMeta: any) {
    const options: RouterGuardOptions = routeMeta?.auth || {};
    return await this.routerGuard.check(options);
  }

  // 检查特定权限
  async checkSpecificPermission(permission: string) {
    return await this.routerGuard.hasPermission(permission);
  }

  // 检查特定角色
  async checkSpecificRole(role: string) {
    return await this.routerGuard.hasRole(role);
  }

  // 获取当前用户信息
  getCurrentUser() {
    return this.routerGuard.getCurrentUser();
  }

  // 处理认证状态变化
  setupAuthListeners() {
    // 监听登录事件
    this.auth.on('login', () => {
      console.log('用户已登录');
      // 可以在这里刷新路由权限等
    });

    // 监听登出事件
    this.auth.on('logout', () => {
      console.log('用户已登出');
      // 可以在这里清理相关状态
    });
  }
}

// 使用示例
export function usageDemo() {
  // 1. 基础使用
  const routerGuard = basicUsageExample();
  
  // 2. 手动权限检查
  manualPermissionCheckExample(routerGuard);
  
  // 3. 获取路由配置
  const routes = vueRouterConfigExample();
  console.log('路由配置:', routes);
  
  // 4. 创建安全路由管理器
  const secureManager = new SecureRouteManager();
  
  // 5. 设置监听器
  secureManager.setupAuthListeners();
  
  return { routerGuard, secureManager };
}