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

export interface TTLHistory {
  carrierId: string;
  origin: string;
  destination: string;
  actualDays: number;
}

/**
 * [BIZ_SC_12] 全球物流履约时效自动预测服务
 * @description 基于历史发货轨迹，预测全球各线路的真实妥投时效
 */
export class LogisticTTLService {
  private static readonly HISTORY_TABLE = 'cf_logistics_ttl_history';

  /**
   * 初始化历史表 (由 index.ts 调用)
   */
  static async initTable(): Promise<void> {
    const hasTable = await db.schema.hasTable(this.HISTORY_TABLE);
    if (!hasTable) {
      console.log(`📦 Creating ${this.HISTORY_TABLE} table...`);
      await db.schema.createTable(this.HISTORY_TABLE, (table) => {
        table.increments('id').primary();
        table.string('carrier_id', 64).notNullable();
        table.string('origin', 64).notNullable();
        table.string('destination', 64).notNullable();
        table.float('actual_days').notNullable();
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
      console.log(`✅ Table ${this.HISTORY_TABLE} created`);
    }
  }

  /**
   * 记录发货历史
   */
  static async recordActualTTL(history: TTLHistory): Promise<void> {
    await db(this.HISTORY_TABLE).insert({
      carrier_id: history.carrierId,
      origin: history.origin,
      destination: history.destination,
      actual_days: history.actualDays
    });
  }

  /**
   * 预测物流时效 (BIZ_SC_12)
   * @description 使用加权平均模型预测未来时效
   */
  static async predictTTL(carrierId: string, origin: string, destination: string): Promise<number> {
    logger.info(`[LogisticsTTL] Predicting TTL for Carrier: ${carrierId}, ${origin} -> ${destination}`);

    // 1. 查找最近 30 天的历史记录
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const history = await db(this.HISTORY_TABLE)
      .where({ carrier_id: carrierId, origin, destination })
      .andWhere('created_at', '>=', thirtyDaysAgo)
      .select('actual_days');

    if (history.length === 0) return 10; // 默认 10 天

    // 2. 简单加权平均 (BIZ_SC_12)
    const sum = history.reduce((acc, curr) => acc + curr.actual_days, 0);
    const avg = sum / history.length;

    // 增加 10% 的缓冲期作为安全边际
    return Math.ceil(avg * 1.1);
  }
}
