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

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

export class AfterSalesDecisionController {
  /**
   * POST /api/v1/after-sales/ai-decision
   * 生成售后审核AI决策
   */
  static async makeDecision(req: Request, res: Response) {
    try {
      const { tenantId, shopId, operatorId, afterSalesId, requestData } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        shopId,
        operatorId,
        businessType: DecisionType.AFTER_SALES,
        operationType: requestData?.type || 'REFUND_REVIEW',
        targetIds: [afterSalesId],
        customParams: {
          afterSalesId,
          type: requestData?.type,
          amount: requestData?.totalAmount,
          isHighValue: (requestData?.totalAmount || 0) > 500,
          isMalicious: false,
          repeated: false,
          hasHistory: false,
        },
      });

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

      return res.json({
        success: true,
        data: aiDecision,
      });
    } catch (error) {
      logger.error('[AfterSalesDecisionController] makeDecision error:', error);
      return res.status(500).json({
        success: false,
        error: 'DECISION_ERROR',
        message: '售后AI决策失败',
      });
    }
  }

  /**
   * POST /api/v1/after-sales/approve
   * 批准售后申请
   */
  static async approve(req: Request, res: Response) {
    try {
      const { tenantId, operatorId, afterSalesId, notes } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        operatorId,
        businessType: DecisionType.AFTER_SALES,
        operationType: 'AFTER_SALES_APPROVE',
        targetIds: [afterSalesId],
      });

      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: '此售后操作需要人工确认',
          },
        });
      }

      logger.info(`[AfterSalesDecisionController] AfterSales approved: ${afterSalesId}`);

      return res.json({
        success: true,
        data: {
          afterSalesId,
          status: 'APPROVED',
          aiDecision,
        },
      });
    } catch (error) {
      logger.error('[AfterSalesDecisionController] approve error:', error);
      return res.status(500).json({
        success: false,
        error: 'APPROVE_ERROR',
        message: '批准售后申请失败',
      });
    }
  }

  /**
   * POST /api/v1/after-sales/reject
   * 拒绝售后申请
   */
  static async reject(req: Request, res: Response) {
    try {
      const { tenantId, operatorId, afterSalesId, reason } = req.body;

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

      logger.info(`[AfterSalesDecisionController] AfterSales rejected: ${afterSalesId}, reason: ${reason}`);

      return res.json({
        success: true,
        data: {
          afterSalesId,
          status: 'REJECTED',
          reason,
        },
      });
    } catch (error) {
      logger.error('[AfterSalesDecisionController] reject error:', error);
      return res.status(500).json({
        success: false,
        error: 'REJECT_ERROR',
        message: '拒绝售后申请失败',
      });
    }
  }

  /**
   * POST /api/v1/after-sales/refund
   * 执行退款
   */
  static async refund(req: Request, res: Response) {
    try {
      const { tenantId, operatorId, afterSalesId, refundAmount, refundMethod } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        operatorId,
        businessType: DecisionType.AFTER_SALES,
        operationType: 'REFUND_EXECUTE',
        targetIds: [afterSalesId],
        customParams: {
          amount: refundAmount,
          isHighValue: refundAmount > 500,
        },
      });

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

      logger.info(`[AfterSalesDecisionController] Refund executed: ${afterSalesId}, amount: ${refundAmount}`);

      return res.json({
        success: true,
        data: {
          afterSalesId,
          refundAmount,
          refundMethod,
          aiDecision,
        },
      });
    } catch (error) {
      logger.error('[AfterSalesDecisionController] refund error:', error);
      return res.status(500).json({
        success: false,
        error: 'REFUND_ERROR',
        message: '执行退款失败',
      });
    }
  }
}
