import db from '../config/database';
import { logger } from '../utils/logger';
import { WarehouseService } from './WarehouseService';

export interface StockDistributionAdvice {
  tenantId: string;
  productId: string;
  fromWarehouseId: string;
  toWarehouseId: string;
  suggestedQuantity: number;
  reason: string;
}

/**
 * [BIZ_TRADE_09] 全球海外仓库存智能分布服务
 * @description 分析区域需求热力图，自动生成库存前置（移仓）建议
 */
export class InventoryDistributionService {
  /**
   * 生成库存分布建议 (BIZ_TRADE_09)
   */
  static async generateDistributionAdvice(tenantId: string): Promise<StockDistributionAdvice[]> {
    logger.info(`[InventoryDist] Analyzing demand for Tenant: ${tenantId}`);

    const advices: StockDistributionAdvice[] = [];

    // 1. 获取所有热销商品及区域需求分布
    // 模拟基于订单历史的需求热力分析
    const products = await db('cf_product').where({ tenant_id: tenantId }).limit(10);

    for (const product of products) {
      const advice = await this.analyzeProductDistribution(tenantId, product.id);
      if (advice) advices.push(advice);
    }

    return advices;
  }

  private static async analyzeProductDistribution(tenantId: string, productId: string): Promise<StockDistributionAdvice | null> {
    // 模拟分析：如果该商品在欧洲销量占比 > 40%，但库存全在国内仓，则建议移仓
    const inventory = await db('cf_inventory').where({ tenant_id: tenantId, product_id: productId });
    
    const localStock = inventory.find(i => i.warehouse_id === 'DEFAULT' || i.warehouse_id === 'LOCAL_01');
    const overseasStock = inventory.find(i => i.warehouse_id === 'OVERSEAS_EU_01');

    if (localStock && localStock.available_stock > 100 && (!overseasStock || overseasStock.available_stock < 20)) {
      return {
        tenantId,
        productId,
        fromWarehouseId: localStock.warehouse_id,
        toWarehouseId: 'OVERSEAS_EU_01',
        suggestedQuantity: 50,
        reason: 'High demand detected in EU region. Forward positioning suggested to reduce delivery time.'
      };
    }

    return null;
  }
}
