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

export interface PackageStatus {
  trackingNumber: string;
  orderId: string;
  carrier: string;
  status: 'PENDING' | 'PICKED_UP' | 'IN_TRANSIT' | 'CUSTOMS' | 'OUT_FOR_DELIVERY' | 'DELIVERED' | 'EXCEPTION';
  location: string;
  timestamp: Date;
  details: string;
}

/**
 * [BIZ_TRADE_10] 跨境物流包裹实时状态遥测 (Logistic Telemetry)
 * @description 核心逻辑：监听物流承运商 Webhook 或主动轮询 API，实时更新包裹状态。
 */
export class LogisticTelemetryService {
  private static readonly TELEMETRY_TABLE = 'cf_logistic_telemetry';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TELEMETRY_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TELEMETRY_TABLE} table...`);
      await db.schema.createTable(this.TELEMETRY_TABLE, (table) => {
        table.increments('id').primary();
        table.string('trackingNumber', 64).notNullable();
        table.string('orderId', 64).notNullable();
        table.string('carrier', 50).notNullable();
        table.string('status', 20).notNullable();
        table.string('location', 255);
        table.timestamp('timestamp');
        table.text('details');
        table.unique(['trackingNumber', 'status', 'timestamp']);
        table.index(['orderId']);
        table.timestamps(true, true);
      });
    }
  }

  /**
   * 更新包裹状态 (由 Webhook 或轮询触发)
   */
  static async updatePackageStatus(status: PackageStatus) {
    logger.info(`[LogisticsTelemetry] Update for ${status.trackingNumber}: ${status.status}`);

    try {
      // 1. 保存遥测流水记录
      await db(this.TELEMETRY_TABLE).insert({
        trackingNumber: status.trackingNumber,
        orderId: status.orderId,
        carrier: status.carrier,
        status: status.status,
        location: status.location,
        timestamp: status.timestamp,
        details: status.details,
        created_at: new Date(),
        updated_at: new Date()
      });

      // 2. 更新订单主表状态
      await db('cf_consumer_orders')
        .where({ id: status.orderId })
        .update({
          logistic_status: status.status,
          last_logistic_update: status.timestamp,
          updated_at: new Date()
        });

      // 3. 触发通知逻辑 (如果需要)
      // ...
    } catch (err: any) {
      logger.error(`[LogisticsTelemetry] Failed for ${status.trackingNumber}: ${err.message}`);
    }
  }

  /**
   * 获取订单的物流追踪历史
   */
  static async getTrackingHistory(orderId: string): Promise<PackageStatus[]> {
    return db(this.TELEMETRY_TABLE)
      .where({ orderId })
      .orderBy('timestamp', 'desc');
  }
}
