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

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

export class InventoryDecisionController {
  /**
   * POST /api/v1/inventory/ai-decision
   * 生成库存调整AI决策
   */
  static async makeDecision(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operatorId,
        productId,
        inventoryId,
        adjustmentType,
        quantity,
        customParams,
      } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        shopId,
        operatorId,
        businessType: DecisionType.INVENTORY,
        operationType: adjustmentType || 'STOCK_ADJUST',
        targetIds: inventoryId ? [inventoryId] : [productId],
        customParams: {
          ...customParams,
          productId,
          inventoryId,
          adjustmentType,
          quantity,
        },
      });

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

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

  /**
   * POST /api/v1/inventory/adjust
   * 执行库存调整
   */
  static async adjustInventory(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operatorId,
        inventoryId,
        productId,
        quantity,
        reason,
      } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        shopId,
        operatorId,
        businessType: DecisionType.INVENTORY,
        operationType: 'STOCK_ADJUST',
        targetIds: [inventoryId],
        customParams: {
          inventoryId,
          productId,
          quantity,
          reason,
        },
      });

      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 updated = await InventoryService.updateInventoryQuantity(inventoryId, quantity);

      logger.info(`[InventoryDecisionController] Inventory adjusted: ${inventoryId}`);

      return res.json({
        success: true,
        data: {
          inventory: updated,
          aiDecision,
        },
      });
    } catch (error) {
      logger.error('[InventoryDecisionController] adjustInventory error:', error);
      return res.status(500).json({
        success: false,
        error: 'ADJUST_ERROR',
        message: '库存调整失败',
      });
    }
  }

  /**
   * POST /api/v1/inventory/reserve
   * 预留库存
   */
  static async reserveInventory(req: Request, res: Response) {
    try {
      const { tenantId, operatorId, inventoryId, quantity } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        operatorId,
        businessType: DecisionType.INVENTORY,
        operationType: 'RESERVE_STOCK',
        targetIds: [inventoryId],
        customParams: { inventoryId, quantity },
      });

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

      const updated = await InventoryService.reserveInventory(inventoryId, quantity);

      return res.json({
        success: true,
        data: { inventory: updated, aiDecision },
      });
    } catch (error) {
      logger.error('[InventoryDecisionController] reserveInventory error:', error);
      return res.status(500).json({
        success: false,
        error: 'RESERVE_ERROR',
        message: '库存预留失败',
      });
    }
  }

  /**
   * POST /api/v1/inventory/release
   * 释放预留库存
   */
  static async releaseInventory(req: Request, res: Response) {
    try {
      const { tenantId, operatorId, inventoryId, quantity } = req.body;

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

      const aiDecision = makeAIDecision({
        tenantId,
        operatorId,
        businessType: DecisionType.INVENTORY,
        operationType: 'RELEASE_STOCK',
        targetIds: [inventoryId],
        customParams: { inventoryId, quantity },
      });

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

      const updated = await InventoryService.releaseInventory(inventoryId, quantity);

      return res.json({
        success: true,
        data: { inventory: updated, aiDecision },
      });
    } catch (error) {
      logger.error('[InventoryDecisionController] releaseInventory error:', error);
      return res.status(500).json({
        success: false,
        error: 'RELEASE_ERROR',
        message: '库存释放失败',
      });
    }
  }

  /**
   * GET /api/v1/inventory/:id
   * 获取库存详情
   */
  static async getInventory(req: Request, res: Response) {
    try {
      const id = req.params.id as string;

      const inventory = await InventoryService.getInventoryById(id);
      if (!inventory) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '库存不存在',
        });
      }

      return res.json({
        success: true,
        data: inventory,
      });
    } catch (error) {
      logger.error('[InventoryDecisionController] getInventory error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_ERROR',
        message: '获取库存失败',
      });
    }
  }
}
