const PermissionService = require('../services/permissionService');
const jwt = require('jsonwebtoken');

/**
 * 权限检查中间件
 * @param {string|string[]} requiredPermissions - 必需的权限代码（单个或数组）
 * @param {string} checkType - 检查类型：'any'（任意一个）或 'all'（全部）
 * @returns {Function} Express中间件函数
 */
const requirePermission = (requiredPermissions, checkType = 'any') => {
  return async (req, res, next) => {
    try {
      // 从请求头获取token
      const token = req.headers.authorization?.replace('Bearer ', '');
      
      if (!token) {
        return res.status(401).json({
          success: false,
          message: '未提供认证令牌'
        });
      }

      // 验证token并获取用户信息
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      const userId = decoded.userId;

      if (!userId) {
        return res.status(401).json({
          success: false,
          message: '无效的认证令牌'
        });
      }

      // 确保权限是数组格式
      const permissions = Array.isArray(requiredPermissions) 
        ? requiredPermissions 
        : [requiredPermissions];

      let hasPermission = false;

      // 根据检查类型进行权限验证
      if (checkType === 'all') {
        hasPermission = await PermissionService.checkUserAllPermissions(userId, permissions);
      } else {
        hasPermission = await PermissionService.checkUserAnyPermission(userId, permissions);
      }

      if (!hasPermission) {
        return res.status(403).json({
          success: false,
          message: '权限不足，无法访问此资源',
          requiredPermissions: permissions
        });
      }

      // 将用户ID添加到请求对象中，供后续使用
      req.userId = userId;
      next();
    } catch (error) {
      console.error('权限检查中间件错误:', error);
      
      if (error.name === 'JsonWebTokenError') {
        return res.status(401).json({
          success: false,
          message: '无效的认证令牌'
        });
      }
      
      if (error.name === 'TokenExpiredError') {
        return res.status(401).json({
          success: false,
          message: '认证令牌已过期'
        });
      }

      return res.status(500).json({
        success: false,
        message: '权限检查失败'
      });
    }
  };
};

/**
 * 检查单个权限的中间件
 * @param {string} permission - 权限代码
 * @returns {Function} Express中间件函数
 */
const requireSinglePermission = (permission) => {
  return requirePermission(permission, 'any');
};

/**
 * 检查多个权限中任意一个的中间件
 * @param {string[]} permissions - 权限代码数组
 * @returns {Function} Express中间件函数
 */
const requireAnyPermission = (permissions) => {
  return requirePermission(permissions, 'any');
};

/**
 * 检查多个权限全部具备的中间件
 * @param {string[]} permissions - 权限代码数组
 * @returns {Function} Express中间件函数
 */
const requireAllPermissions = (permissions) => {
  return requirePermission(permissions, 'all');
};

/**
 * 管理员权限检查中间件
 * @returns {Function} Express中间件函数
 */
const requireAdmin = () => {
  return requireSinglePermission('system:admin');
};

/**
 * 超级管理员权限检查中间件
 * @returns {Function} Express中间件函数
 */
const requireSuperAdmin = () => {
  return requireSinglePermission('system:super_admin');
};

/**
 * 权限检查装饰器（用于控制器方法）
 * @param {string|string[]} permissions - 权限代码
 * @param {string} checkType - 检查类型
 * @returns {Function} 装饰器函数
 */
const withPermission = (permissions, checkType = 'any') => {
  return (target, propertyKey, descriptor) => {
    const originalMethod = descriptor.value;
    
    descriptor.value = async function(req, res, next) {
      try {
        const middleware = requirePermission(permissions, checkType);
        await new Promise((resolve, reject) => {
          middleware(req, res, (err) => {
            if (err) reject(err);
            else resolve();
          });
        });
        
        return originalMethod.call(this, req, res, next);
      } catch (error) {
        return res.status(403).json({
          success: false,
          message: '权限不足'
        });
      }
    };
    
    return descriptor;
  };
};

/**
 * 动态权限检查中间件
 * 根据请求参数动态确定所需权限
 * @param {Function} permissionResolver - 权限解析函数
 * @returns {Function} Express中间件函数
 */
const requireDynamicPermission = (permissionResolver) => {
  return async (req, res, next) => {
    try {
      const requiredPermissions = await permissionResolver(req);
      const middleware = requirePermission(requiredPermissions);
      return middleware(req, res, next);
    } catch (error) {
      console.error('动态权限检查失败:', error);
      return res.status(500).json({
        success: false,
        message: '权限检查失败'
      });
    }
  };
};

module.exports = {
  requirePermission,
  requireSinglePermission,
  requireAnyPermission,
  requireAllPermissions,
  requireAdmin,
  requireSuperAdmin,
  withPermission,
  requireDynamicPermission
};