/**
 * [BE-BATCH-001] 批量操作AI接管中间件
 * 负责判断批量操作是否由AI自动执行
 * AI注意: 所有批量操作API必须通过此中间件校验
 */

import { NextFunction, Request, Response } from 'express';
import {
  BatchOperationType,
  BatchOperationStatus,
  BATCH_OPERATION_AI_CONFIG,
  AI_CAN_AUTO_EXECUTE,
} from '../../shared/types/batch-operation';
import { logger } from '../../utils/logger';

declare global {
  namespace Express {
    interface Request {
      batchAIValidation?: {
        allowed: boolean;
        autoExecute: boolean;
        reason: string;
        confidence: number;
        riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
        requiredAction: 'AUTO_EXECUTE' | 'PENDING_REVIEW' | 'HUMAN_ONLY';
        subscriptionLevel: 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE';
        warnings: string[];
      };
    }
  }
}

interface BatchOperationRequest {
  tenantId: string;
  shopId: string;
  operatorId: string;
  operationType: BatchOperationType;
  targetIds: string[];
  targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
  subscriptionLevel?: 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE';
  estimatedImpact?: {
    amount?: number;
    quantity?: number;
  };
}

const calculateRiskLevel = (
  operationType: BatchOperationType,
  targetCount: number,
  estimatedImpact?: { amount?: number; quantity?: number }
): 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' => {
  if (operationType === BatchOperationType.BATCH_EDIT_CATEGORY ||
      operationType === BatchOperationType.BATCH_EDIT_COD ||
      operationType === BatchOperationType.BATCH_EDIT_SELLER_SKU) {
    return 'HIGH';
  }

  if (estimatedImpact?.amount) {
    if (estimatedImpact.amount > 50000) return 'CRITICAL';
    if (estimatedImpact.amount > 10000) return 'HIGH';
    if (estimatedImpact.amount > 1000) return 'MEDIUM';
  }

  if (targetCount > 100) return 'HIGH';
  if (targetCount > 50) return 'MEDIUM';

  return 'LOW';
};

const calculateConfidence = (
  operationType: BatchOperationType,
  targetCount: number,
  subscriptionLevel: string
): number => {
  let baseConfidence = 0.9;

  switch (operationType) {
    case BatchOperationType.BATCH_EDIT_PRICE:
    case BatchOperationType.BATCH_EDIT_INVENTORY:
      baseConfidence = 0.95;
      break;
    case BatchOperationType.BATCH_EDIT_TITLE:
    case BatchOperationType.BATCH_LISTING:
    case BatchOperationType.BATCH_DELIST:
      baseConfidence = 0.75;
      break;
    default:
      baseConfidence = 0.6;
  }

  if (targetCount > 50) {
    baseConfidence -= 0.1;
  }

  const levelBonus: Record<string, number> = {
    ENTERPRISE: 0.1,
    PROFESSIONAL: 0.05,
    BASIC: 0,
    FREE: -0.2,
  };

  return Math.min(1, Math.max(0, baseConfidence + (levelBonus[subscriptionLevel] || 0)));
};

export const validateBatchOperationAI = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const body: BatchOperationRequest = req.body;

    if (!body.tenantId || !body.operatorId || !body.operationType) {
      return res.status(400).json({
        success: false,
        error: 'MISSING_REQUIRED_FIELDS',
        message: '缺少必要字段: tenantId, operatorId, operationType',
      });
    }

    const subscriptionLevel = body.subscriptionLevel || 'FREE';
    const config = BATCH_OPERATION_AI_CONFIG[subscriptionLevel];

    if (!config) {
      return res.status(400).json({
        success: false,
        error: 'INVALID_SUBSCRIPTION_LEVEL',
        message: '无效的订阅等级',
      });
    }

    const canAIExecute = AI_CAN_AUTO_EXECUTE[body.operationType];
    const targetCount = body.targetIds?.length || 0;
    const riskLevel = calculateRiskLevel(body.operationType, targetCount, body.estimatedImpact);
    const confidence = calculateConfidence(body.operationType, targetCount, subscriptionLevel);

    const warnings: string[] = [];
    if (targetCount > (config.maxAutoQuantity ?? 0)) {
      warnings.push(`操作数量 ${targetCount} 超过最大自动执行数量 ${config.maxAutoQuantity}`);
    }
    if (body.estimatedImpact?.amount && body.estimatedImpact.amount > (config.maxAutoBudget ?? 0)) {
      warnings.push(`操作金额 ${body.estimatedImpact.amount} 超过最大自动执行预算 ${config.maxAutoBudget}`);
    }
    if (!config.allowedRiskLevels.includes(riskLevel)) {
      warnings.push(`风险等级 ${riskLevel} 不在允许范围内`);
    }

    let requiredAction: 'AUTO_EXECUTE' | 'PENDING_REVIEW' | 'HUMAN_ONLY';
    let autoExecute = false;
    let reason: string;

    if (!canAIExecute) {
      requiredAction = 'HUMAN_ONLY';
      reason = `${body.operationType} 类型操作不支持AI自动执行`;
    } else if (confidence >= config.autoExecuteConfidence && config.allowedRiskLevels.includes(riskLevel)) {
      requiredAction = 'AUTO_EXECUTE';
      autoExecute = true;
      reason = `AI自动执行: 置信度 ${(confidence * 100).toFixed(1)}% >= ${(config.autoExecuteConfidence * 100).toFixed(1)}%, 风险等级 ${riskLevel} 在允许范围内`;
    } else if (confidence >= config.pendingReviewConfidence) {
      requiredAction = 'PENDING_REVIEW';
      reason = `需要人工确认: 置信度 ${(confidence * 100).toFixed(1)}% < ${(config.autoExecuteConfidence * 100).toFixed(1)}% 或风险等级 ${riskLevel} 不在允许范围内`;
    } else {
      requiredAction = 'PENDING_REVIEW';
      reason = `需要人工确认: 置信度 ${(confidence * 100).toFixed(1)}% < ${(config.pendingReviewConfidence * 100).toFixed(1)}%`;
    }

    req.batchAIValidation = {
      allowed: requiredAction !== 'HUMAN_ONLY',
      autoExecute,
      reason,
      confidence,
      riskLevel,
      requiredAction,
      subscriptionLevel: subscriptionLevel as 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE',
      warnings,
    };

    logger.info(`[BatchOperationAIMiddleware] Validation result: ${JSON.stringify(req.batchAIValidation)}`);

    next();
  } catch (error) {
    logger.error('[BatchOperationAIMiddleware] Validation error:', error);
    return res.status(500).json({
      success: false,
      error: 'VALIDATION_ERROR',
      message: '批量操作AI校验失败',
    });
  }
};

export const requireHumanConfirmation = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const validation = req.batchAIValidation;

  if (!validation) {
    return res.status(400).json({
      success: false,
      error: 'MISSING_VALIDATION',
      message: '缺少批量操作AI校验信息，请先通过 validateBatchOperationAI 中间件',
    });
  }

  if (validation.requiredAction === 'AUTO_EXECUTE') {
    return res.status(200).json({
      success: true,
      autoExecute: true,
      message: validation.reason,
      confidence: validation.confidence,
    });
  }

  if (validation.requiredAction === 'HUMAN_ONLY') {
    return res.status(403).json({
      success: false,
      error: 'AI_NOT_ALLOWED',
      message: validation.reason,
      subscriptionLevel: validation.subscriptionLevel,
    });
  }

  next();
};

export const checkBatchOperationPermission = (
  requiredSubscriptionLevel: 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE'
) => {
  const levelOrder: Record<string, number> = {
    FREE: 0,
    BASIC: 1,
    PROFESSIONAL: 2,
    ENTERPRISE: 3,
  };

  return (req: Request, res: Response, next: NextFunction) => {
    const userLevel = req.batchAIValidation?.subscriptionLevel || 'FREE';

    if ((levelOrder[userLevel] || 0) < (levelOrder[requiredSubscriptionLevel] || 0)) {
      return res.status(403).json({
        success: false,
        error: 'INSUFFICIENT_SUBSCRIPTION',
        message: `此操作需要 ${requiredSubscriptionLevel} 级别或更高订阅`,
        currentLevel: userLevel,
        requiredLevel: requiredSubscriptionLevel,
      });
    }

    next();
  };
};
