/**
 * [BE-CTL-015] 智能定价建议控制器
 * 提供智能定价建议的RESTful API接口
 * AI注意: 所有智能定价建议必须通过此控制器
 */

import { Request, Response } from 'express';
import { SmartPricingService } from '../../services/core/SmartPricingService';
import {
  validateAIDecision,
  makeAIDecision,
  DecisionType,
  DecisionResult,
} from '../middleware/AIDecisionMiddleware';
import { logger } from '../../utils/logger';

export class SmartPricingController {
  /**
   * POST /api/v1/smart-pricing/recommend
   * 生成智能定价建议
   */
  static async generateRecommendation(req: Request, res: Response) {
    try {
      const {
        tenantId,
        productId,
        platform,
        strategy,
        businessType,
      } = req.body;

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

      const recommendation = await SmartPricingService.generatePricingRecommendation({
        tenantId,
        productId,
        platform,
        strategy,
        businessType,
      });

      const aiDecision = makeAIDecision({
        tenantId,
        shopId: '',
        operatorId: 'system',
        businessType: DecisionType.PRICING,
        operationType: 'SMART_PRICING_RECOMMEND',
        targetIds: [productId],
        customParams: {
          recommendationId: recommendation.recommendationId,
          strategy: recommendation.strategy,
          confidence: recommendation.confidence,
          priceChangePercent: recommendation.priceChangePercent,
        },
      });

      logger.info(`[SmartPricingController] Recommendation generated: ${recommendation.recommendationId}`);

      return res.json({
        success: true,
        data: {
          recommendation,
          aiDecision,
        },
      });
    } catch (error) {
      logger.error('[SmartPricingController] generateRecommendation error:', error);
      return res.status(500).json({
        success: false,
        error: 'GENERATE_ERROR',
        message: '生成智能定价建议失败',
      });
    }
  }

  /**
   * POST /api/v1/smart-pricing/simulate
   * 模拟定价方案
   */
  static async simulate(req: Request, res: Response) {
    try {
      const {
        tenantId,
        productId,
        platform,
        priceRange,
        steps,
      } = req.body;

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

      const simulations = await SmartPricingService.simulatePricing({
        tenantId,
        productId,
        platform,
        priceRange,
        steps,
      });

      return res.json({
        success: true,
        data: simulations,
      });
    } catch (error) {
      logger.error('[SmartPricingController] simulate error:', error);
      return res.status(500).json({
        success: false,
        error: 'SIMULATE_ERROR',
        message: '模拟定价方案失败',
      });
    }
  }

  /**
   * POST /api/v1/smart-pricing/apply
   * 应用定价建议
   */
  static async applyRecommendation(req: Request, res: Response) {
    try {
      const {
        recommendationId,
        tenantId,
        approvedBy,
      } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        shopId: '',
        operatorId: approvedBy,
        businessType: DecisionType.PRICING,
        operationType: 'APPLY_PRICING_RECOMMENDATION',
        targetIds: [recommendationId],
      });

      if (aiDecision.requiredAction === DecisionResult.HUMAN_ONLY) {
        return res.status(403).json({
          success: false,
          error: 'AI_NOT_ALLOWED',
          message: '此操作仅支持人工处理',
          aiDecision,
        });
      }

      if (aiDecision.requiredAction === DecisionResult.PENDING_REVIEW) {
        return res.status(200).json({
          success: true,
          data: {
            requiresConfirmation: true,
            aiDecision,
            message: '此操作需要人工确认',
          },
        });
      }

      const result = await SmartPricingService.applyRecommendation({
        recommendationId,
        tenantId,
        approvedBy,
      });

      logger.info(`[SmartPricingController] Recommendation applied: ${recommendationId}`);

      return res.json({
        success: true,
        data: result,
      });
    } catch (error) {
      logger.error('[SmartPricingController] applyRecommendation error:', error);
      return res.status(500).json({
        success: false,
        error: 'APPLY_ERROR',
        message: '应用定价建议失败',
      });
    }
  }

  /**
   * GET /api/v1/smart-pricing/recommendations
   * 获取活跃定价建议列表
   */
  static async getActiveRecommendations(req: Request, res: Response) {
    try {
      const { tenantId, productId, platform, limit } = req.query;

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

      const recommendations = await SmartPricingService.getActiveRecommendations({
        tenantId: tenantId as string,
        productId: productId as string,
        platform: platform as string,
        limit: limit ? parseInt(limit as string) : 20,
      });

      return res.json({
        success: true,
        data: recommendations,
      });
    } catch (error) {
      logger.error('[SmartPricingController] getActiveRecommendations error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_ERROR',
        message: '获取定价建议列表失败',
      });
    }
  }

  /**
   * POST /api/v1/smart-pricing/batch
   * 批量生成定价建议
   */
  static async batchGenerate(req: Request, res: Response) {
    try {
      const {
        tenantId,
        productIds,
        platform,
        strategy,
      } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        shopId: '',
        operatorId: 'system',
        businessType: DecisionType.PRICING,
        operationType: 'BATCH_SMART_PRICING',
        targetIds: productIds,
        customParams: {
          count: productIds.length,
        },
      });

      const recommendations = await SmartPricingService.batchGenerateRecommendations({
        tenantId,
        productIds,
        platform,
        strategy,
      });

      logger.info(`[SmartPricingController] Batch recommendations generated: ${recommendations.length}/${productIds.length}`);

      return res.json({
        success: true,
        data: {
          recommendations,
          aiDecision,
          total: productIds.length,
          success: recommendations.length,
          failed: productIds.length - recommendations.length,
        },
      });
    } catch (error) {
      logger.error('[SmartPricingController] batchGenerate error:', error);
      return res.status(500).json({
        success: false,
        error: 'BATCH_ERROR',
        message: '批量生成定价建议失败',
      });
    }
  }

  /**
   * GET /api/v1/smart-pricing/history
   * 获取定价历史
   */
  static async getPriceHistory(req: Request, res: Response) {
    try {
      const { tenantId, productId, platform, limit } = req.query;

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

      const history = await SmartPricingService.getPriceHistory({
        tenantId: tenantId as string,
        productId: productId as string,
        platform: platform as string,
        limit: limit ? parseInt(limit as string) : 30,
      });

      return res.json({
        success: true,
        data: history,
      });
    } catch (error) {
      logger.error('[SmartPricingController] getPriceHistory error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_ERROR',
        message: '获取定价历史失败',
      });
    }
  }
}
