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

export interface CarbonCreditTransaction {
  id?: string;
  tenant_id: string;
  order_id: string;
  credits_purchased: number; // kg CO2
  cost_amount: number;
  provider_did: string;
  status: 'PENDING' | 'SETTLED' | 'CANCELLED';
  created_at?: Date;
}

/**
 * [BIZ_LOG_60] 绿色供应链碳信用交易撮合 (Carbon Credit Trading)
 * @description 聚合租户碳足迹数据，撮合碳抵扣额度购买。
 */
export class CarbonCreditTradingService {
  private static readonly TRANSACTION_TABLE = 'cf_carbon_credit_transactions';

  /**
   * 撮合订单级碳抵扣交易
   */
  static async matchOffsetTransaction(tenantId: string, orderId: string) {
    logger.info(`[CarbonTrading] Matching offset transaction for order: ${orderId}`);

    // 1. 获取该订单的碳足迹 (联动 GreenSupplyChainService)
    const orderFootprint = await db('cf_carbon_footprints')
      .where({ tenant_id: tenantId, order_id: orderId })
      .first();

    if (!orderFootprint || orderFootprint.status === 'OFFSET_COMPLETED') {
      logger.info(`[CarbonTrading] No pending footprint found for order ${orderId}`);
      return null;
    }

    // 2. 构造撮合记录
    const tx: CarbonCreditTransaction = {
      tenant_id: tenantId,
      order_id: orderId,
      credits_purchased: orderFootprint.total_co2,
      cost_amount: orderFootprint.offset_cost,
      provider_did: 'DID-CARBON-POOL-GLOBAL',
      status: 'PENDING',
      created_at: new Date()
    };

    const [id] = await db(this.TRANSACTION_TABLE).insert(tx);
    
    // 3. 模拟与外部碳交易池握手
    logger.info(`[CarbonTrading] Match proposal sent to carbon pool, ID: ${id}`);

    return tx;
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TRANSACTION_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TRANSACTION_TABLE} table...`);
      await db.schema.createTable(this.TRANSACTION_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('order_id', 64).notNullable().index();
        table.decimal('credits_purchased', 15, 2);
        table.decimal('cost_amount', 15, 2);
        table.string('provider_did', 128).notNullable();
        table.string('status', 32).defaultTo('PENDING');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }
}
