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

export interface ReplenishmentPlan {
  tenantId: string;
  productId: string;
  suggestedQuantity: number;
  expectedRestockDate: Date;
}

/**
 * [BIZ_TRADE_05] 智能补货决策模型
 * @description 结合安全库存、交期预测与供应商评分，自动生成补货单
 */
export class ReplenishmentService {
  private static readonly PLAN_TABLE = 'cf_replenishment_plans';

  /**
   * 初始化表 (由 index.ts 调用)
   */
  static async initTable(): Promise<void> {
    const hasTable = await db.schema.hasTable(this.PLAN_TABLE);
    if (!hasTable) {
      console.log(`📦 Creating ${this.PLAN_TABLE} table...`);
      await db.schema.createTable(this.PLAN_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('product_id', 64).notNullable();
        table.integer('suggested_quantity').notNullable();
        table.timestamp('expected_restock_date');
        table.string('status', 16).defaultTo('PENDING'); // PENDING, ORDERED, CANCELLED
        table.timestamps(true, true);
        table.index(['tenant_id', 'status']);
      });
      console.log(`✅ Table ${this.PLAN_TABLE} created`);
    }
  }

  /**
   * 运行补货分析 (BIZ_TRADE_05)
   */
  static async runAnalysis(tenantId: string, productId: string): Promise<void> {
    logger.info(`[Replenishment] Running analysis for Product: ${productId}, Tenant: ${tenantId}`);

    // 1. 获取库存与销量速度 (BIZ_TRADE_05)
    const stock = await db('cf_inventory').where({ tenant_id: tenantId, product_id: productId }).first();
    if (!stock) return;

    // 模拟销量速度 (最近 7 天日均)
    const velocity = 5; 
    const currentStock = stock.available_stock;

    // 2. 获取预测交期 (BIZ_SC_12)
    const bestSupplierId = await SupplierService.recommendBestSupplier(productId, tenantId);
    const predictedTTL = await LogisticTTLService.predictTTL('CARRIER_DEFAULT', 'CN', 'US');

    // 3. 补货计算 (BIZ_TRADE_05)
    // 补货点 = 预测交期 * 销量速度 + 安全库存
    const safetyStock = 10;
    const reorderPoint = predictedTTL * velocity + safetyStock;

    if (currentStock <= reorderPoint) {
      const quantity = Math.ceil(velocity * 30); // 补足 30 天销量
      const restockDate = new Date();
      restockDate.setDate(restockDate.getDate() + predictedTTL);

      await db(this.PLAN_TABLE).insert({
        tenant_id: tenantId,
        product_id: productId,
        suggested_quantity: quantity,
        expected_restock_date: restockDate,
        status: 'PENDING',
        created_at: new Date(),
        updated_at: new Date()
      });

      logger.info(`[Replenishment] Plan generated: ${quantity} units for ${productId}`);
    }
  }
}
