import db from '../config/database';
import { AuditService } from './AuditService';
import { InventoryDistributionService } from './InventoryDistributionService';

/**
 * [BIZ_TRADE_15] 基于预测的库存前置移仓执行
 * 负责接收 InventoryDistributionService 的预测建议，并自动发起跨仓调拨任务
 */
export class PredictiveStagingService {
  /**
   * 自动发起预测性移仓
   */
  static async autoStageInventory(tenantId: string, traceId: string): Promise<void> {
    // 1. 获取库存分布建议 (模拟调用 InventoryDistributionService)
    const suggestions = await InventoryDistributionService.getAdvice(tenantId);
    
    // 2. 筛选高置信度的调拨建议 (confidence > 0.8)
    const highConfidenceAdvice = suggestions.filter(s => s.confidence > 0.8);

    for (const advice of highConfidenceAdvice) {
      await db.transaction(async (trx) => {
        // 创建移仓任务记录
        const [id] = await trx('cf_inventory_staging').insert({
          tenant_id: tenantId,
          product_id: advice.metadata.productId,
          from_warehouse_id: 'DEFAULT', // 假设从主仓出发
          to_warehouse_id: advice.metadata.targetWarehouse,
          quantity: advice.metadata.suggestedQuantity,
          reason: advice.title,
          status: 'PENDING'
        });

        // 模拟发起跨仓调拨 (Transfer Order)
        await trx('cf_transfer_orders').insert({
          id: `TR-${Date.now()}-${id}`,
          tenant_id: tenantId,
          product_id: advice.metadata.productId,
          from_warehouse_id: 'DEFAULT',
          to_warehouse_id: advice.metadata.targetWarehouse,
          quantity: advice.metadata.suggestedQuantity,
          status: 'PENDING_TRANSFER',
          trace_id: traceId
        });

        // 审计记录
        await AuditService.log({
          tenant_id: tenantId,
          action: 'PREDICTIVE_STAGING_START',
          target_type: 'INVENTORY_STAGING',
          target_id: id.toString(),
          trace_id: traceId,
          new_data: JSON.stringify({ productId: advice.metadata.productId, quantity: advice.metadata.suggestedQuantity }),
          metadata: JSON.stringify({ confidence: advice.confidence, reason: advice.title })
        });
      });
    }
  }

  /**
   * 获取租户所有移仓任务状态
   */
  static async getStagingStatus(tenantId: string) {
    return await db('cf_inventory_staging')
      .where({ tenant_id: tenantId })
      .orderBy('created_at', 'desc');
  }
}
