/**
 * 权限路由守卫
 * 根据用户权限控制页面访问
 */

import type { Router } from 'vue-router'
import type { Permission } from '../auth/roles'
import { usePermission } from '../composables/usePermission'

export interface RoutePermission {
  /** 路由名称 */
  name: string
  /** 所需权限 */
  requiredPermissions?: Permission[]
  /** 所需角色 */
  requiredRoles?: string[]
  /** 是否需要登录 */
  requiresAuth?: boolean
}

/**
 * 默认路由权限配置
 * 注意: 路由名称需要与 router/index.ts 中的 name 保持一致 (kebab-case)
 */
export const routePermissions: RoutePermission[] = [
  // 仪表盘
  { name: 'dashboard', requiredPermissions: ['dashboard.index.view.ALL'] },

  // 用户管理
  { name: 'users', requiredPermissions: ['user.index.view.ALL'] },
  { name: 'user-detail', requiredPermissions: ['user.index.view.ALL'] },

  // 活动管理
  { name: 'activities', requiredPermissions: ['activity.index.view.ALL'] },
  { name: 'activity-detail', requiredPermissions: ['activity.index.view.ALL'] },
  { name: 'activity-create', requiredPermissions: ['activity.index.create.ALL'] },
  { name: 'activity-config', requiredPermissions: ['activity.index.create.ALL'] },

  // 奖励管理
  { name: 'rewards', requiredPermissions: ['reward.index.view.ALL'] },

  // 风险管理
  { name: 'risk', requiredPermissions: ['risk.index.view.ALL'] },

  // 审批中心
  { name: 'approvals', requiredPermissions: ['approval.index.view.ALL'] },

  // 审计日志
  { name: 'audit', requiredPermissions: ['audit.index.view.ALL'] },

  // 系统配置
  { name: 'system-config', requiredPermissions: ['system.index.view.ALL'] },

  // 权限管理
  { name: 'permissions', requiredPermissions: ['permission.index.view.ALL'] },

  // 邀请用户
  { name: 'user-invite', requiredPermissions: ['user.index.create.ALL'] },

  // 通知
  { name: 'notifications', requiredPermissions: ['notification.index.view.ALL'] },

  // 角色管理
  { name: 'role-management', requiredPermissions: ['permission.index.view.ALL'] },

  // 部门管理
  { name: 'department-management', requiredPermissions: ['permission.index.view.ALL'] }
]

/**
 * 创建权限路由守卫
 */
export function createPermissionGuard(router: Router) {
  const { hasPermission, hasRole, initialized } = usePermission()

  router.beforeEach(async (to, from, next) => {
    // 等待权限初始化
    if (!initialized.value) {
      await new Promise(resolve => {
        const checkInit = setInterval(() => {
          if (initialized.value) {
            clearInterval(checkInit)
            resolve(true)
          }
        }, 100)
        // 超时5秒后继续
        setTimeout(() => {
          clearInterval(checkInit)
          resolve(true)
        }, 5000)
      })
    }

    // 检查路由权限
    const routePermission = routePermissions.find(rp => rp.name === to.name)

    if (routePermission) {
      // 检查所需权限
      if (routePermission.requiredPermissions?.length) {
        const hasRequired = routePermission.requiredPermissions.some(permission =>
          hasPermission(permission as Permission)
        )
        if (!hasRequired) {
          // 没有权限，跳转到403页面
          return next({ name: 'forbidden' })
        }
      }

      // 检查所需角色
      if (routePermission.requiredRoles?.length) {
        const hasRequiredRole = routePermission.requiredRoles.some(role =>
          hasRole(role as any)
        )
        if (!hasRequiredRole) {
          return next({ name: 'forbidden' })
        }
      }
    }

    next()
  })
}

/**
 * 检查路由是否有权限访问
 */
export function canAccessRoute(routeName: string): boolean {
  const { hasPermission } = usePermission()
  const routePermission = routePermissions.find(rp => rp.name === routeName)

  if (!routePermission) {
    return true // 没有配置权限的路由默认允许访问
  }

  if (routePermission.requiredPermissions?.length) {
    return routePermission.requiredPermissions.some(permission =>
      hasPermission(permission as Permission)
    )
  }

  if (routePermission.requiredRoles?.length) {
    const { hasRole } = usePermission()
    return routePermission.requiredRoles.some(role => hasRole(role as any))
  }

  return true
}
