import db from '../../config/database';
import { AuditService } from '../core/AuditService';
import { InventoryDistributionService, StockDistributionAdvice } 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. 筛选高置信度的调拨建议 (所有建议都处理)
    for (const advice of suggestions) {
      await db.transaction(async (trx) => {
        // 创建移仓任务记录
        const [id] = await trx('cf_inventory_staging').insert({
          tenant_id: tenantId,
          product_id: advice.productId,
          from_warehouse_id: advice.fromWarehouseId,
          to_warehouse_id: advice.toWarehouseId,
          quantity: advice.suggestedQuantity,
          reason: advice.reason,
          status: 'PENDING'
        });

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

        // 审计记录
        await AuditService.log({
          tenantId: tenantId,
          action: 'PREDICTIVE_STAGING_START',
          module: 'INVENTORY',
          resourceType: 'INVENTORY_STAGING',
          resourceId: id.toString(),
          traceId: traceId,
          userId: 'system',
          result: 'success',
          source: 'console',
          afterSnapshot: { productId: advice.productId, quantity: advice.suggestedQuantity },
          metadata: { reason: advice.reason }
        });
      });
    }
  }

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