import { Request, Response, NextFunction } from 'express';
import { RBACEngine } from '../auth/RBACEngine';
import { logger } from '../../utils/logger';

/**
 * [BIZ_RBAC_01] RBAC 权限校验门禁
 * @param requiredPermission 所需权限点 (如 'product:write')
 */
export const requirePermission = (requiredPermission: string) => {
  return async (req: Request, res: Response, next: NextFunction) => {
    const context = (req as any).traceContext;

    if (!context || !context.userId || !context.tenantId) {
      logger.error(`[RBAC] Missing auth context for request ${req.path}`);
      return res.status(401).json({ 
        success: false, 
        error: 'Unauthorized: Missing security context' 
      });
    }

    // [V32.0] 使用 RBACEngine.authorize 进行异步权限校验
    const hasAccess = await RBACEngine.authorize(context.userId, context.tenantId, requiredPermission);

    if (!hasAccess) {
      logger.warn(`[RBAC] User ${context.userId} denied permission [${requiredPermission}] for tenant ${context.tenantId}`);
      return res.status(403).json({ 
        success: false, 
        error: `Forbidden: Missing required permission [${requiredPermission}]` 
      });
    }

    next();
  };
};
