/**
 * [BE-AIAUTO-003] 自动执行阈值校验中间件
 * 负责在AI决策执行前进行阈值校验和权限验证
 * AI注意: 所有自动执行决策API必须通过此中间件校验
 */

import { NextFunction, Request, Response } from 'express';
import { AutoExecutionConfigService, DecisionModule, RiskLevel, ExecutionRequest } from '../services/AutoExecutionConfigService';
import { AIDecisionLogService } from '../services/AIDecisionLogService';
import { logger } from '../utils/logger';

// 扩展Request类型
declare global {
  namespace Express {
    interface Request {
      autoExecutionValidation?: {
        allowed: boolean;
        reason: string;
        required_action: 'AUTO_EXECUTE' | 'PENDING_REVIEW' | 'AUTO_REJECT';
        config_snapshot: any;
        warnings: string[];
      };
    }
  }
}

// 决策执行请求Schema
interface DecisionExecutionRequest {
  tenant_id: string;
  shop_id: string;
  module: DecisionModule;
  decision_type: string;
  confidence: number;
  risk_level: RiskLevel;
  estimated_impact: {
    amount?: number;
    quantity?: number;
  };
  input_data: any;
  output_data: any;
  metadata?: Record<string, any>;
}

/**
 * 自动执行阈值校验中间件
 * 在执行AI决策前校验配置和阈值
 */
export const validateAutoExecution = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const body: DecisionExecutionRequest = req.body;
    
    // 必填字段校验
    if (!body.tenant_id || !body.shop_id || !body.module) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段: tenant_id, shop_id, module',
      });
    }

    // 置信度范围校验
    if (body.confidence < 0 || body.confidence > 1) {
      return res.status(400).json({
        success: false,
        error: 'INVALID_CONFIDENCE',
        message: '置信度必须在 0-1 之间',
      });
    }

    // 风险等级校验
    const validRiskLevels: RiskLevel[] = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
    if (!validRiskLevels.includes(body.risk_level)) {
      return res.status(400).json({
        success: false,
        error: 'INVALID_RISK_LEVEL',
        message: `风险等级必须是: ${validRiskLevels.join(', ')}`,
      });
    }

    // 构建执行请求
    const executionRequest: ExecutionRequest = {
      tenant_id: body.tenant_id,
      shop_id: body.shop_id,
      module: body.module,
      decision_id: `DEC-${Date.now()}`,
      confidence: body.confidence,
      risk_level: body.risk_level,
      estimated_impact: body.estimated_impact || {},
      metadata: body.metadata,
    };

    // 执行校验
    const validationResult = await AutoExecutionConfigService.validateExecution(executionRequest);
    
    // 将校验结果附加到请求对象
    req.autoExecutionValidation = validationResult;

    // 记录决策日志
    const traceId = req.headers['x-trace-id'] as string || `TRC-${Date.now()}`;
    const taskId = req.headers['x-task-id'] as string || `TSK-${Date.now()}`;
    
    await AIDecisionLogService.createLog(
      body.tenant_id,
      body.shop_id,
      taskId,
      traceId,
      body.module as any,
      'TOC',
      {
        context: body.metadata || {},
        parameters: body.input_data,
        constraints: { risk_level: body.risk_level, estimated_impact: body.estimated_impact },
      },
      {
        decision: validationResult.required_action,
        confidence: body.confidence,
        reasoning: validationResult.reason,
        alternatives: [],
        expected_result: { allowed: validationResult.allowed },
      }
    );

    // 根据校验结果决定下一步
    if (validationResult.required_action === 'AUTO_REJECT') {
      logger.warn(`[AutoExecution] Auto-rejected: ${validationResult.reason}`);
      return res.status(403).json({
        success: false,
        error: 'AUTO_REJECTED',
        message: validationResult.reason,
        warnings: validationResult.warnings,
        config_snapshot: validationResult.config_snapshot,
      });
    }

    if (validationResult.required_action === 'PENDING_REVIEW') {
      logger.info(`[AutoExecution] Pending review: ${validationResult.reason}`);
      // 允许继续，但标记需要审核
      req.autoExecutionValidation = {
        ...validationResult,
        allowed: false,
      };
    }

    // 记录校验通过
    logger.info(`[AutoExecution] Validation passed for ${body.module}: ${validationResult.required_action}`);
    next();
  } catch (error) {
    logger.error('[AutoExecution] Validation error:', error);
    return res.status(500).json({
      success: false,
      error: 'VALIDATION_ERROR',
      message: '自动执行校验失败',
      details: error instanceof Error ? error.message : 'Unknown error',
    });
  }
};

/**
 * 仅允许自动执行的中间件
 * 如果需要审核则拒绝请求
 */
export const requireAutoExecute = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const validation = req.autoExecutionValidation;
  
  if (!validation) {
    return res.status(500).json({
      success: false,
      error: 'MISSING_VALIDATION',
      message: '缺少自动执行校验结果，请先执行 validateAutoExecution 中间件',
    });
  }

  if (validation.required_action !== 'AUTO_EXECUTE') {
    return res.status(403).json({
      success: false,
      error: 'MANUAL_REVIEW_REQUIRED',
      message: validation.reason,
      required_action: validation.required_action,
      warnings: validation.warnings,
    });
  }

  next();
};

/**
 * 审核权限校验中间件
 * 确保只有有权限的用户可以审核待执行的决策
 */
export const requireReviewPermission = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const user = (req as any).user;
    if (!user) {
      return res.status(401).json({
        success: false,
        error: 'UNAUTHORIZED',
        message: '未登录',
      });
    }

    // 检查用户角色权限
    const allowedRoles = ['ADMIN', 'MANAGER', 'OPERATOR'];
    if (!allowedRoles.includes(user.role)) {
      return res.status(403).json({
        success: false,
        error: 'FORBIDDEN',
        message: '无审核权限',
      });
    }

    next();
  } catch (error) {
    logger.error('[AutoExecution] Review permission check error:', error);
    return res.status(500).json({
      success: false,
      error: 'PERMISSION_CHECK_ERROR',
      message: '权限校验失败',
    });
  }
};

/**
 * 等级升级权限校验中间件
 * 只有ADMIN可以升级自动化等级
 */
export const requireLevelChangePermission = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const user = (req as any).user;
    if (!user) {
      return res.status(401).json({
        success: false,
        error: 'UNAUTHORIZED',
        message: '未登录',
      });
    }

    // 只有ADMIN可以修改自动化等级
    if (user.role !== 'ADMIN') {
      return res.status(403).json({
        success: false,
        error: 'FORBIDDEN',
        message: '只有管理员可以修改自动化等级',
      });
    }

    next();
  } catch (error) {
    logger.error('[AutoExecution] Level change permission check error:', error);
    return res.status(500).json({
      success: false,
      error: 'PERMISSION_CHECK_ERROR',
      message: '权限校验失败',
    });
  }
};

/**
 * 执行结果记录中间件
 * 在决策执行后记录结果并更新统计
 */
export const recordExecutionResult = (
  module: DecisionModule,
  getTenantId: (req: Request) => string,
  getShopId: (req: Request) => string
) => {
  return async (req: Request, res: Response, next: NextFunction) => {
    // 保存原始的json方法
    const originalJson = res.json.bind(res);
    
    // 重写json方法
    res.json = function(body: any): Response {
      // 只在响应成功时记录
      if (body && body.success !== false) {
        const confidence = req.body?.confidence || 0.8;
        const rolledBack = body?.rolledBack || false;
        
        // 异步记录执行结果
        AutoExecutionConfigService.recordExecution(
          getTenantId(req),
          getShopId(req),
          module,
          true,
          confidence,
          rolledBack
        ).catch(err => {
          logger.error('[AutoExecution] Failed to record execution result:', err);
        });
      } else if (body && body.success === false) {
        const confidence = req.body?.confidence || 0.8;
        
        AutoExecutionConfigService.recordExecution(
          getTenantId(req),
          getShopId(req),
          module,
          false,
          confidence,
          false
        ).catch(err => {
          logger.error('[AutoExecution] Failed to record execution result:', err);
        });
      }
      
      return originalJson(body);
    };
    
    next();
  };
};
