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

export interface CrowdsourcedDeliveryRequest {
  orderId: string;
  origin: string;
  destination: string;
  weight: number;
  maxCost?: number;
}

/**
 * [BIZ_LOG_30] 最后一公里众包路由优化 (Crowdsourced Last-mile)
 * @description 在传统物流瘫痪时，自动调度众包资源并核算成本。
 */
export class CrowdsourcedLogisticsService {
  private static readonly REQUEST_TABLE = 'cf_crowdsourced_requests';
  private static readonly AGENT_TABLE = 'cf_crowdsourced_agents';

  /**
   * 调度众包资源
   */
  static async scheduleDelivery(tenantId: string, request: CrowdsourcedDeliveryRequest) {
    logger.info(`[Crowdsourced] Scheduling delivery for order: ${request.orderId}`);

    // 1. 查找可用众包代理 (基于目的地)
    const availableAgents = await db(this.AGENT_TABLE)
      .where({ status: 'ACTIVE', city: request.destination.split(',')[0] });

    if (availableAgents.length === 0) {
      logger.warn(`[Crowdsourced] No available agents found for ${request.destination}`);
      return null;
    }

    // 2. 选择最优代理 (基于评分、成本)
    const sortedAgents = availableAgents.sort((a, b) => a.base_cost - b.base_cost);
    const selectedAgent = sortedAgents[0];

    const estimatedCost = selectedAgent.base_cost + (request.weight * 0.5); // 基础费 + 续重费

    // 3. 记录请求并分配代理
    const requestId = `CSL-${request.orderId}-${Date.now()}`;
    const scheduleRecord = {
      id: requestId,
      tenant_id: tenantId,
      order_id: request.orderId,
      agent_did: selectedAgent.did,
      origin: request.origin,
      destination: request.destination,
      weight: request.weight,
      estimated_cost: Number(estimatedCost.toFixed(2)),
      status: 'ASSIGNED',
      created_at: new Date()
    };

    await db(this.REQUEST_TABLE).insert(scheduleRecord);

    logger.info(`[Crowdsourced] Assigned agent ${selectedAgent.did} for order ${request.orderId}`);

    return scheduleRecord;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasAgentTable = await db.schema.hasTable(this.AGENT_TABLE);
    if (!hasAgentTable) {
      logger.info(`📦 Creating ${this.AGENT_TABLE} table...`);
      await db.schema.createTable(this.AGENT_TABLE, (table) => {
        table.string('did', 128).primary();
        table.string('city', 64).notNullable();
        table.decimal('base_cost', 15, 2);
        table.integer('rating').defaultTo(100);
        table.string('status', 32).defaultTo('ACTIVE');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['city', 'status']);
      });
    }

    const hasRequestTable = await db.schema.hasTable(this.REQUEST_TABLE);
    if (!hasRequestTable) {
      logger.info(`📦 Creating ${this.REQUEST_TABLE} table...`);
      await db.schema.createTable(this.REQUEST_TABLE, (table) => {
        table.string('id', 128).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('order_id', 64).notNullable();
        table.string('agent_did', 128);
        table.string('origin', 256);
        table.string('destination', 256);
        table.decimal('weight', 10, 2);
        table.decimal('estimated_cost', 15, 2);
        table.string('status', 32);
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'order_id']);
        table.index(['agent_did']);
      });
    }
  }
}
