/**
 * [BE-CTL-013] AI批量操作建议控制器
 * 提供AI批量操作建议的API接口
 * AI注意: 所有AI批量操作建议API必须通过此控制器
 */

import { Request, Response } from 'express';
import { BatchOperationService } from '../../services/core/BatchOperationService';
import { logger } from '../../utils/logger';
import {
  BatchOperationType,
  BatchOperationStatus,
  BATCH_OPERATION_AI_CONFIG,
  OPERATION_TYPE_LABELS,
} from '../../shared/types/batch-operation';

interface AISuggestion {
  id: string;
  tenantId: string;
  shopId: string;
  operationType: BatchOperationType;
  targetType: 'PRODUCT' | 'AD_CAMPAIGN' | 'AD_CREATIVE';
  targetIds: string[];
  targetCount: number;
  confidence: number;
  reason: string;
  recommendedValue: Record<string, any>;
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  estimatedImpact: {
    amount?: number;
    quantity?: number;
  };
  subscriptionLevel: 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE';
  status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'EXPIRED';
  createdAt: Date;
  expiresAt: Date;
}

export class AIBatchController {
  private static suggestions: Map<string, AISuggestion> = new Map();

  /**
   * GET /api/v1/ai/batch-suggestions
   * 获取AI批量操作建议列表
   */
  static async getSuggestions(req: Request, res: Response) {
    try {
      const { tenantId, shopId, status, operationType, page, pageSize } = req.query;

      if (!tenantId) {
        return res.status(400).json({
          success: false,
          error: 'MISSING_TENANT_ID',
          message: '缺少租户ID',
        });
      }

      let suggestions = Array.from(this.suggestions.values())
        .filter((s) => s.tenantId === tenantId);

      if (shopId) {
        suggestions = suggestions.filter((s) => s.shopId === shopId);
      }
      if (status) {
        suggestions = suggestions.filter((s) => s.status === status);
      }
      if (operationType) {
        suggestions = suggestions.filter((s) => s.operationType === operationType);
      }

      const now = new Date();
      suggestions = suggestions.filter((s) => s.expiresAt > now && s.status === 'PENDING');

      const total = suggestions.length;
      const pageNum = page ? parseInt(page as string) : 1;
      const pageSizeNum = pageSize ? parseInt(pageSize as string) : 20;
      const start = (pageNum - 1) * pageSizeNum;
      const paginatedSuggestions = suggestions.slice(start, start + pageSizeNum);

      return res.json({
        success: true,
        data: paginatedSuggestions,
        total,
        page: pageNum,
        pageSize: pageSizeNum,
      });
    } catch (error) {
      logger.error('[AIBatchController] getSuggestions error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_SUGGESTIONS_ERROR',
        message: '获取AI建议失败',
      });
    }
  }

  /**
   * GET /api/v1/ai/batch-suggestions/:id
   * 获取单个AI建议详情
   */
  static async getSuggestionById(req: Request, res: Response) {
    try {
      const id = req.params.id as string;

      const suggestion = this.suggestions.get(id);
      if (!suggestion) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: 'AI建议不存在',
        });
      }

      return res.json({
        success: true,
        data: suggestion,
      });
    } catch (error) {
      logger.error('[AIBatchController] getSuggestionById error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_SUGGESTION_ERROR',
        message: '获取AI建议详情失败',
      });
    }
  }

  /**
   * POST /api/v1/ai/batch-suggestions/:id/approve
   * 批准AI批量操作建议
   */
  static async approveSuggestion(req: Request, res: Response) {
    try {
      const id = req.params.id as string;
      const { tenantId, operatorId, operatorName } = req.body;

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

      const suggestion = this.suggestions.get(id);
      if (!suggestion) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: 'AI建议不存在',
        });
      }

      if (suggestion.status !== 'PENDING') {
        return res.status(400).json({
          success: false,
          error: 'INVALID_STATUS',
          message: `当前状态不允许批准: ${suggestion.status}`,
        });
      }

      if (suggestion.expiresAt < new Date()) {
        return res.status(400).json({
          success: false,
          error: 'EXPIRED',
          message: 'AI建议已过期',
        });
      }

      suggestion.status = 'APPROVED';

      const batchRecord = await BatchOperationService.createBatchOperation({
        tenantId: suggestion.tenantId,
        shopId: suggestion.shopId,
        operatorId: operatorId,
        operatorName: operatorName || 'AI Approved',
        operationType: suggestion.operationType,
        targetType: suggestion.targetType,
        targetIds: suggestion.targetIds,
      });

      await BatchOperationService.updateBatchOperation(batchRecord.id, {
        status: BatchOperationStatus.AWAITING_CONFIRM,
        aiConfidence: suggestion.confidence,
        aiReason: suggestion.reason,
        riskLevel: suggestion.riskLevel,
        subscriptionLevel: suggestion.subscriptionLevel,
        aiAutoExecuted: false,
      });

      logger.info(`[AIBatchController] Approved AI suggestion: ${id}, created batch: ${batchRecord.id}`);

      return res.json({
        success: true,
        data: {
          suggestionId: id,
          batchId: batchRecord.id,
          message: 'AI建议已批准，已创建批量操作待执行',
        },
      });
    } catch (error) {
      logger.error('[AIBatchController] approveSuggestion error:', error);
      return res.status(500).json({
        success: false,
        error: 'APPROVE_ERROR',
        message: '批准AI建议失败',
      });
    }
  }

  /**
   * POST /api/v1/ai/batch-suggestions/:id/reject
   * 拒绝AI批量操作建议
   */
  static async rejectSuggestion(req: Request, res: Response) {
    try {
      const id = req.params.id as string;
      const { tenantId, operatorId, reason } = req.body;

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

      const suggestion = this.suggestions.get(id);
      if (!suggestion) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: 'AI建议不存在',
        });
      }

      if (suggestion.status !== 'PENDING') {
        return res.status(400).json({
          success: false,
          error: 'INVALID_STATUS',
          message: `当前状态不允许拒绝: ${suggestion.status}`,
        });
      }

      suggestion.status = 'REJECTED';

      logger.info(`[AIBatchController] Rejected AI suggestion: ${id}, reason: ${reason || 'No reason provided'}`);

      return res.json({
        success: true,
        data: {
          suggestionId: id,
          message: 'AI建议已拒绝',
        },
      });
    } catch (error) {
      logger.error('[AIBatchController] rejectSuggestion error:', error);
      return res.status(500).json({
        success: false,
        error: 'REJECT_ERROR',
        message: '拒绝AI建议失败',
      });
    }
  }

  /**
   * POST /api/v1/ai/batch/analyze
   * AI分析批量操作（生成建议）
   */
  static async analyze(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operationType,
        targetType,
        targetIds,
        targetData,
        subscriptionLevel,
      } = req.body;

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

      const config = BATCH_OPERATION_AI_CONFIG[subscriptionLevel || 'BASIC'];
      const targetCount = targetIds.length;

      let confidence = 0.8;
      switch (operationType) {
        case BatchOperationType.BATCH_EDIT_PRICE:
        case BatchOperationType.BATCH_EDIT_INVENTORY:
          confidence = 0.9;
          break;
        case BatchOperationType.BATCH_LISTING:
        case BatchOperationType.BATCH_DELIST:
          confidence = 0.75;
          break;
        default:
          confidence = 0.6;
      }

      if (targetCount > 50) confidence -= 0.1;
      if (targetCount > 100) confidence -= 0.15;

      const riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' =
        targetCount > 100 ? 'HIGH' :
        targetCount > 50 ? 'MEDIUM' : 'LOW';

      const estimatedImpact = {
        quantity: targetCount,
        amount: targetData?.totalAmount || targetCount * 100,
      };

      const reason = `AI分析了${targetCount}个目标，建议执行${OPERATION_TYPE_LABELS[operationType as BatchOperationType]}操作。` +
        `风险等级: ${riskLevel}，置信度: ${(confidence * 100).toFixed(0)}%。`;

      const suggestion: AISuggestion = {
        id: `suggestion-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        tenantId,
        shopId: shopId || '',
        operationType: operationType as BatchOperationType,
        targetType,
        targetIds,
        targetCount,
        confidence,
        reason,
        recommendedValue: targetData || {},
        riskLevel,
        estimatedImpact,
        subscriptionLevel: (subscriptionLevel || 'BASIC') as 'FREE' | 'BASIC' | 'PROFESSIONAL' | 'ENTERPRISE',
        status: 'PENDING',
        createdAt: new Date(),
        expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
      };

      this.suggestions.set(suggestion.id, suggestion);

      logger.info(`[AIBatchController] Created AI suggestion: ${suggestion.id}`);

      return res.json({
        success: true,
        data: {
          suggestionId: suggestion.id,
          confidence: suggestion.confidence,
          riskLevel: suggestion.riskLevel,
          reason: suggestion.reason,
          estimatedImpact: suggestion.estimatedImpact,
          autoExecute: confidence >= config.autoExecuteConfidence && config.allowedRiskLevels.includes(riskLevel),
        },
      });
    } catch (error) {
      logger.error('[AIBatchController] analyze error:', error);
      return res.status(500).json({
        success: false,
        error: 'ANALYZE_ERROR',
        message: 'AI分析失败',
      });
    }
  }

  /**
   * GET /api/v1/ai/batch-suggestions/stats
   * 获取AI建议统计
   */
  static async getStats(req: Request, res: Response) {
    try {
      const { tenantId } = req.query;

      if (!tenantId) {
        return res.status(400).json({
          success: false,
          error: 'MISSING_TENANT_ID',
          message: '缺少租户ID',
        });
      }

      const suggestions = Array.from(this.suggestions.values())
        .filter((s) => s.tenantId === tenantId);

      const now = new Date();
      const validSuggestions = suggestions.filter((s) => s.expiresAt > now);

      const stats = {
        total: suggestions.length,
        pending: validSuggestions.filter((s) => s.status === 'PENDING').length,
        approved: suggestions.filter((s) => s.status === 'APPROVED').length,
        rejected: suggestions.filter((s) => s.status === 'REJECTED').length,
        expired: suggestions.filter((s) => s.expiresAt <= now).length,
        byOperationType: {} as Record<string, number>,
        byRiskLevel: {
          LOW: validSuggestions.filter((s) => s.riskLevel === 'LOW').length,
          MEDIUM: validSuggestions.filter((s) => s.riskLevel === 'MEDIUM').length,
          HIGH: validSuggestions.filter((s) => s.riskLevel === 'HIGH').length,
          CRITICAL: validSuggestions.filter((s) => s.riskLevel === 'CRITICAL').length,
        },
        averageConfidence: validSuggestions.length > 0
          ? validSuggestions.reduce((sum, s) => sum + s.confidence, 0) / validSuggestions.length
          : 0,
      };

      for (const suggestion of validSuggestions) {
        const type = suggestion.operationType;
        stats.byOperationType[type] = (stats.byOperationType[type] || 0) + 1;
      }

      return res.json({
        success: true,
        data: stats,
      });
    } catch (error) {
      logger.error('[AIBatchController] getStats error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_STATS_ERROR',
        message: '获取统计失败',
      });
    }
  }
}
