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

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

export class BatchOperationController {
  /**
   * POST /api/v1/batch/validate
   * 校验批量操作是否可由AI执行
   */
  static async validate(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operatorId,
        operationType,
        targetIds,
        targetType,
        subscriptionLevel,
        estimatedImpact,
      } = req.body;

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

      req.body = {
        tenantId,
        shopId,
        operatorId,
        operationType,
        targetIds,
        targetType,
        subscriptionLevel,
        estimatedImpact,
      };

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

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

      return res.status(500).json({
        success: false,
        error: 'VALIDATION_FAILED',
        message: '校验失败',
      });
    } catch (error) {
      logger.error('[BatchOperationController] validate error:', error);
      return res.status(500).json({
        success: false,
        error: 'VALIDATION_ERROR',
        message: '批量操作AI校验失败',
      });
    }
  }

  /**
   * POST /api/v1/batch/create
   * 创建批量操作记录
   */
  static async create(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operatorId,
        operatorName,
        operationType,
        targetType,
        targetIds,
        subscriptionLevel,
      } = req.body;

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

      const record = await BatchOperationService.createBatchOperation({
        tenantId,
        shopId,
        operatorId,
        operatorName,
        operationType: operationType as BatchOperationType,
        targetType,
        targetIds,
      });

      await BatchOperationService.updateBatchOperation(record.id, {
        subscriptionLevel,
        status: BatchOperationStatus.PENDING,
      });

      logger.info(`[BatchOperationController] Created batch operation: ${record.id}`);

      return res.json({
        success: true,
        data: record,
      });
    } catch (error) {
      logger.error('[BatchOperationController] create error:', error);
      return res.status(500).json({
        success: false,
        error: 'CREATE_ERROR',
        message: '创建批量操作失败',
      });
    }
  }

  /**
   * POST /api/v1/batch/:id/execute
   * 执行批量操作
   */
  static async execute(req: Request, res: Response) {
    try {
      const id = req.params.id as string;
      const { params } = req.body;

      const batch = await BatchOperationService.getBatchOperation(id);
      if (!batch) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '批量操作记录不存在',
        });
      }

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

      const result = await BatchOperationService.executeBatchOperation(id, params || {});

      logger.info(`[BatchOperationController] Executed batch operation: ${id}, success: ${result.success}`);

      return res.json({
        success: result.success,
        data: result,
      });
    } catch (error) {
      logger.error('[BatchOperationController] execute error:', error);
      return res.status(500).json({
        success: false,
        error: 'EXECUTE_ERROR',
        message: '执行批量操作失败',
      });
    }
  }

  /**
   * POST /api/v1/batch/:id/confirm
   * 确认执行批量操作（人工确认）
   */
  static async confirm(req: Request, res: Response) {
    try {
      const id = req.params.id as string;

      const batch = await BatchOperationService.getBatchOperation(id);
      if (!batch) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '批量操作记录不存在',
        });
      }

      if (batch.status !== BatchOperationStatus.AWAITING_CONFIRM) {
        return res.status(400).json({
          success: false,
          error: 'INVALID_STATUS',
          message: `当前状态不允许确认: ${batch.status}`,
        });
      }

      await BatchOperationService.updateBatchOperation(id, {
        status: BatchOperationStatus.EXECUTING,
        confirmedAt: new Date(),
      });

      const result = await BatchOperationService.executeBatchOperation(id);

      logger.info(`[BatchOperationController] Confirmed batch operation: ${id}`);

      return res.json({
        success: true,
        data: { batchId: id, ...result },
      });
    } catch (error) {
      logger.error('[BatchOperationController] confirm error:', error);
      return res.status(500).json({
        success: false,
        error: 'CONFIRM_ERROR',
        message: '确认批量操作失败',
      });
    }
  }

  /**
   * POST /api/v1/batch/:id/cancel
   * 取消批量操作
   */
  static async cancel(req: Request, res: Response) {
    try {
      const id = req.params.id as string;

      const batch = await BatchOperationService.getBatchOperation(id);
      if (!batch) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '批量操作记录不存在',
        });
      }

      if (batch.status === BatchOperationStatus.COMPLETED ||
          batch.status === BatchOperationStatus.FAILED) {
        return res.status(400).json({
          success: false,
          error: 'INVALID_STATUS',
          message: `当前状态不允许取消: ${batch.status}`,
        });
      }

      await BatchOperationService.updateBatchOperation(id, {
        status: BatchOperationStatus.CANCELLED,
      });

      logger.info(`[BatchOperationController] Cancelled batch operation: ${id}`);

      return res.json({
        success: true,
      });
    } catch (error) {
      logger.error('[BatchOperationController] cancel error:', error);
      return res.status(500).json({
        success: false,
        error: 'CANCEL_ERROR',
        message: '取消批量操作失败',
      });
    }
  }

  /**
   * GET /api/v1/batch/:id
   * 获取批量操作详情
   */
  static async getOne(req: Request, res: Response) {
    try {
      const id = req.params.id as string;

      const batch = await BatchOperationService.getBatchOperation(id);
      if (!batch) {
        return res.status(404).json({
          success: false,
          error: 'NOT_FOUND',
          message: '批量操作记录不存在',
        });
      }

      return res.json({
        success: true,
        data: batch,
      });
    } catch (error) {
      logger.error('[BatchOperationController] getOne error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_ERROR',
        message: '获取批量操作详情失败',
      });
    }
  }

  /**
   * GET /api/v1/batch/history
   * 获取批量操作历史
   */
  static async getHistory(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operationType,
        status,
        startDate,
        endDate,
        page,
        pageSize,
      } = req.query;

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

      const result = await BatchOperationService.getBatchOperationHistory({
        tenantId: tenantId as string,
        shopId: shopId as string,
        operationType: operationType as BatchOperationType,
        status: status as BatchOperationStatus,
        startDate: startDate ? new Date(startDate as string) : undefined,
        endDate: endDate ? new Date(endDate as string) : undefined,
        page: page ? parseInt(page as string) : 1,
        pageSize: pageSize ? parseInt(pageSize as string) : 20,
      });

      return res.json({
        success: true,
        data: result.records,
        total: result.total,
        page: page ? parseInt(page as string) : 1,
        pageSize: pageSize ? parseInt(pageSize as string) : 20,
      });
    } catch (error) {
      logger.error('[BatchOperationController] getHistory error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_HISTORY_ERROR',
        message: '获取批量操作历史失败',
      });
    }
  }

  /**
   * GET /api/v1/batch/summary
   * 获取批量操作统计摘要
   */
  static async getSummary(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 summary = await BatchOperationService.getOperationSummary(tenantId as string);

      return res.json({
        success: true,
        data: summary,
      });
    } catch (error) {
      logger.error('[BatchOperationController] getSummary error:', error);
      return res.status(500).json({
        success: false,
        error: 'GET_SUMMARY_ERROR',
        message: '获取批量操作统计失败',
      });
    }
  }

  /**
   * POST /api/v1/batch/edit/price
   * 批量修改价格
   */
  static async editPrice(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operatorId,
        productIds,
        priceChange,
      } = req.body;

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

      const result = await BatchOperationService.batchEditPrice({
        productIds,
        priceChange,
      });

      logger.info(`[BatchOperationController] Batch edit price: ${productIds.length} products`);

      return res.json({
        success: result.success,
        data: result,
      });
    } catch (error) {
      logger.error('[BatchOperationController] editPrice error:', error);
      return res.status(500).json({
        success: false,
        error: 'EDIT_PRICE_ERROR',
        message: '批量修改价格失败',
      });
    }
  }

  /**
   * POST /api/v1/batch/edit/inventory
   * 批量修改库存
   */
  static async editInventory(req: Request, res: Response) {
    try {
      const {
        tenantId,
        shopId,
        operatorId,
        productIds,
        inventoryChange,
      } = req.body;

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

      const result = await BatchOperationService.batchEditInventory({
        productIds,
        inventoryChange,
      });

      logger.info(`[BatchOperationController] Batch edit inventory: ${productIds.length} products`);

      return res.json({
        success: result.success,
        data: result,
      });
    } catch (error) {
      logger.error('[BatchOperationController] editInventory error:', error);
      return res.status(500).json({
        success: false,
        error: 'EDIT_INVENTORY_ERROR',
        message: '批量修改库存失败',
      });
    }
  }
}
