/**
 * [BE-CTL-014] 定价决策AI控制器
 * 提供定价决策的AI介入RESTful API接口
 * AI注意: 所有定价AI决策必须通过此控制器
 */

import { Request, Response } from 'express';
import { DynamicPricingService } from '../../services/core/DynamicPricingService';
import {
  validateAIDecision,
  requireAIDecision,
  makeAIDecision,
  DecisionType,
  DecisionResult,
  RiskLevel,
} from '../middleware/AIDecisionMiddleware';
import { logger } from '../../utils/logger';
import { PricingDecisionStatus } from '../../types/enums';

export class PricingDecisionController {
  /**
   * POST /api/v1/pricing/ai-decision
   * 生成定价AI决策
   */
  static async makeDecision(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operatorId,
        productId,
        strategy,
        customParams,
      } = req.body;

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

      const decision = makeAIDecision({
        tenantId,
        shopId,
        operatorId,
        businessType: DecisionType.PRICING,
        operationType: strategy || 'AUTO_PRICE_ADJUST',
        customParams: {
          ...customParams,
          productId,
        },
      });

      logger.info(`[PricingDecisionController] AI decision made: ${decision.requiredAction}`);

      return res.json({
        success: true,
        data: decision,
      });
    } catch (error) {
      logger.error('[PricingDecisionController] makeDecision error:', error);
      return res.status(500).json({
        success: false,
        error: 'DECISION_ERROR',
        message: '定价AI决策失败',
      });
    }
  }

  /**
   * POST /api/v1/pricing/validate
   * 校验定价操作是否可由AI执行
   */
  static async validate(req: Request, res: Response, next: Function) {
    try {
      req.body.businessType = DecisionType.PRICING;
      req.body.operationType = req.body.operationType || 'PRICE_ADJUST';

      await new Promise<void>((resolve, reject) => {
        validateAIDecision(req, res, (err?: any) => {
          if (err) reject(err);
          else resolve();
        });
      });

      if (req.aiDecision) {
        return res.json({
          success: true,
          data: req.aiDecision,
        });
      }

      return res.status(500).json({
        success: false,
        error: 'VALIDATION_FAILED',
        message: '校验失败',
      });
    } catch (error) {
      logger.error('[PricingDecisionController] validate error:', error);
      return res.status(500).json({
        success: false,
        error: 'VALIDATION_ERROR',
        message: '定价AI校验失败',
      });
    }
  }

  /**
   * POST /api/v1/pricing/decisions
   * 创建定价决策
   */
  static async createDecision(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        productId,
        strategy,
        subscriptionLevel,
      } = req.body;

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

      const pricingDecision = await DynamicPricingService.generatePricingDecision(
        tenantId,
        shopId,
        productId,
        strategy
      );

      const aiDecision = makeAIDecision({
        tenantId,
        shopId,
        operatorId: 'system',
        businessType: DecisionType.PRICING,
        operationType: strategy || 'AUTO_PRICE_ADJUST',
        targetIds: [productId],
        customParams: {
          subscriptionLevel,
          productId,
          currentPrice: pricingDecision.current_price,
          suggestedPrice: pricingDecision.suggested_price,
          priceChangePercent: pricingDecision.change_percent,
        },
      });

      logger.info(`[PricingDecisionController] Decision created: ${pricingDecision.id}`);

      return res.json({
        success: true,
        data: {
          pricingDecision,
          aiDecision,
        },
      });
    } catch (error) {
      logger.error('[PricingDecisionController] createDecision error:', error);
      return res.status(500).json({
        success: false,
        error: 'CREATE_ERROR',
        message: '创建定价决策失败',
      });
    }
  }

  /**
   * POST /api/v1/pricing/decisions/:id/execute
   * 执行定价决策
   */
  static async executeDecision(req: Request, res: Response) {
    try {
      const id = req.params.id as string;
      const { userId, operatorId } = req.body;

      if (!userId && !operatorId) {
        return res.status(400).json({
          success: false,
          error: 'MISSING_OPERATOR',
          message: '缺少操作人信息',
        });
      }

      const decision = await DynamicPricingService.getPricingDecision(id);
      if (!decision) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '定价决策不存在',
        });
      }

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

      const aiDecision = makeAIDecision({
        tenantId: decision.tenant_id,
        shopId: decision.shop_id,
        operatorId: operatorId || userId,
        businessType: DecisionType.PRICING,
        operationType: 'PRICE_EXECUTE',
        targetIds: [decision.product_id],
        customParams: {
          decisionId: id,
          currentPrice: decision.current_price,
          suggestedPrice: decision.suggested_price,
          priceChangePercent: decision.change_percent,
        },
      });

      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 DynamicPricingService.executePricingDecision(
        id,
        operatorId || userId
      );

      logger.info(`[PricingDecisionController] Decision ${id} executed`);

      return res.json({
        success: result.success,
        data: {
          result,
          aiDecision,
        },
      });
    } catch (error) {
      logger.error('[PricingDecisionController] executeDecision error:', error);
      return res.status(500).json({
        success: false,
        error: 'EXECUTE_ERROR',
        message: '执行定价决策失败',
      });
    }
  }

  /**
   * POST /api/v1/pricing/decisions/:id/approve
   * 人工批准定价决策
   */
  static async approveDecision(req: Request, res: Response) {
    try {
      const id = req.params.id as string;
      const { userId, notes } = req.body;

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

      const decision = await DynamicPricingService.getPricingDecision(id);
      if (!decision) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '定价决策不存在',
        });
      }

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

      const result = await DynamicPricingService.executePricingDecision(id, userId);

      logger.info(`[PricingDecisionController] Decision ${id} approved by ${userId}`);

      return res.json({
        success: result.success,
        data: {
          message: result.message,
          decisionId: id,
        },
      });
    } catch (error) {
      logger.error('[PricingDecisionController] approveDecision error:', error);
      return res.status(500).json({
        success: false,
        error: 'APPROVE_ERROR',
        message: '批准定价决策失败',
      });
    }
  }

  /**
   * POST /api/v1/pricing/decisions/:id/reject
   * 人工拒绝定价决策
   */
  static async rejectDecision(req: Request, res: Response) {
    try {
      const id = req.params.id as string;
      const { userId, reason } = req.body;

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

      const decision = await DynamicPricingService.getPricingDecision(id);
      if (!decision) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '定价决策不存在',
        });
      }

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

      await DynamicPricingService.updatePricingDecisionStatus(
        id,
        PricingDecisionStatus.REJECTED,
        userId,
        reason
      );

      logger.info(`[PricingDecisionController] Decision ${id} rejected by ${userId}: ${reason}`);

      return res.json({
        success: true,
        data: {
          decisionId: id,
          message: '定价决策已拒绝',
        },
      });
    } catch (error) {
      logger.error('[PricingDecisionController] rejectDecision error:', error);
      return res.status(500).json({
        success: false,
        error: 'REJECT_ERROR',
        message: '拒绝定价决策失败',
      });
    }
  }

  /**
   * GET /api/v1/pricing/decisions
   * 获取定价决策列表
   */
  static async getDecisions(req: Request, res: Response) {
    try {
      const { tenantId, shopId, status, startDate, endDate, page, pageSize } = req.query;

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

      const decisions = await DynamicPricingService.getPendingDecisions(
        tenantId as string,
        shopId as string | undefined,
      );

      return res.json({
        success: true,
        data: decisions,
        total: decisions.length,
      });
    } catch (error) {
      logger.error('[PricingDecisionController] getDecisions error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_ERROR',
        message: '获取定价决策列表失败',
      });
    }
  }

  /**
   * GET /api/v1/pricing/decisions/:id
   * 获取单个定价决策详情
   */
  static async getDecisionById(req: Request, res: Response) {
    try {
      const id = req.params.id as string;

      const decision = await DynamicPricingService.getPricingDecision(id);
      if (!decision) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '定价决策不存在',
        });
      }

      return res.json({
        success: true,
        data: decision,
      });
    } catch (error) {
      logger.error('[PricingDecisionController] getDecisionById error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_ERROR',
        message: '获取定价决策详情失败',
      });
    }
  }

  /**
   * GET /api/v1/pricing/decisions/stats
   * 获取定价决策统计
   */
  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 stats = {
        totalDecisions: 0,
        pendingDecisions: 0,
        executedDecisions: 0,
        averageConfidence: 0,
      };

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