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

export interface CarbonCredit {
  id?: number;
  tenantId: string;
  amount: number; // 碳信用额度 (单位：吨 CO2e)
  source: 'RENEWABLE_ENERGY' | 'REFORESTATION' | 'SUPPLY_CHAIN_OPT';
  status: 'AVAILABLE' | 'RESERVED' | 'RETIRED';
  expiresAt: Date;
}

export interface CarbonTransaction {
  id?: number;
  buyerTenantId: string;
  sellerTenantId: string;
  amount: number;
  pricePerUnit: number;
  currency: string;
  timestamp: Date;
}

/**
 * [BIZ_TRADE_23] 主权碳信用交易引擎 (Sovereign Carbon)
 * @description 核心逻辑：建立租户间去中心化的碳信用交易市场。
 * 联动 [CarbonNeutralPathService] 获取租户减排数据并转化为可交易的碳信用。
 * 支持主权节点间的碳配额撮合、定价与自动清算，助力全球绿色供应链转型。
 */
export class SovereignCarbonService {
  private static readonly CREDIT_TABLE = 'cf_carbon_credits';
  private static readonly TRANSACTION_TABLE = 'cf_carbon_transactions';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasCreditTable = await db.schema.hasTable(this.CREDIT_TABLE);
    if (!hasCreditTable) {
      logger.info(`📦 Creating ${this.CREDIT_TABLE} table...`);
      await db.schema.createTable(this.CREDIT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.float('amount').notNullable();
        table.string('source', 32).notNullable();
        table.string('status', 16).defaultTo('AVAILABLE');
        table.timestamp('expires_at');
        table.timestamps(true, true);
      });
    }

    const hasTxTable = await db.schema.hasTable(this.TRANSACTION_TABLE);
    if (!hasTxTable) {
      logger.info(`📦 Creating ${this.TRANSACTION_TABLE} table...`);
      await db.schema.createTable(this.TRANSACTION_TABLE, (table) => {
        table.increments('id').primary();
        table.string('buyer_tenant_id', 64).notNullable();
        table.string('seller_tenant_id', 64).notNullable();
        table.float('amount').notNullable();
        table.float('price_per_unit').notNullable();
        table.string('currency', 8).defaultTo('USD');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 发布可交易碳信用 (基于减排证明)
   */
  static async mintCredits(params: {
    tenantId: string;
    amount: number;
    source: CarbonCredit['source'];
    proofHash: string; // 关联减排证明链
  }): Promise<number> {
    const [id] = await db(this.CREDIT_TABLE).insert({
      tenant_id: params.tenantId,
      amount: params.amount,
      source: params.source,
      expires_at: new Date(Date.now() + 365 * 24 * 3600 * 1000) // 1年有效期
    });
    
    logger.info(`[SovereignCarbon] Minted ${params.amount} credits for Tenant ${params.tenantId}`);
    return id;
  }

  /**
   * 执行碳信用交易 (撮合结算)
   */
  static async tradeCredits(params: {
    buyerTenantId: string;
    sellerTenantId: string;
    amount: number;
    price: number;
  }): Promise<boolean> {
    logger.info(`[SovereignCarbon] Trading ${params.amount} credits from ${params.sellerTenantId} to ${params.buyerTenantId}`);

    return await db.transaction(async (trx) => {
      // 1. 检查卖家余额
      const sellerCredits = await trx(this.CREDIT_TABLE)
        .where({ tenant_id: params.sellerTenantId, status: 'AVAILABLE' })
        .sum('amount as total');
      
      if ((sellerCredits[0]?.total || 0) < params.amount) {
        throw new Error('Insufficient carbon credits available for trade.');
      }

      // 2. 扣减卖家额度 (简单处理：消耗最早到期的)
      await trx(this.CREDIT_TABLE)
        .where({ tenant_id: params.sellerTenantId, status: 'AVAILABLE' })
        .limit(1) // 模拟
        .update({ amount: db.raw(`amount - ${params.amount}`) });

      // 3. 增加买家额度
      await trx(this.CREDIT_TABLE).insert({
        tenant_id: params.buyerTenantId,
        amount: params.amount,
        source: 'SUPPLY_CHAIN_OPT',
        status: 'AVAILABLE'
      });

      // 4. 记录交易
      await trx(this.TRANSACTION_TABLE).insert({
        buyer_tenant_id: params.buyerTenantId,
        seller_tenant_id: params.sellerTenantId,
        amount: params.amount,
        price_per_unit: params.price
      });

      return true;
    });
  }

  /**
   * 获取租户碳中和状态报告
   */
  static async getCarbonStatus(tenantId: string) {
    const credits = await db(this.CREDIT_TABLE).where({ tenant_id: tenantId }).sum('amount as total');
    const transactions = await db(this.TRANSACTION_TABLE)
      .where({ buyer_tenant_id: tenantId })
      .orWhere({ seller_tenant_id: tenantId })
      .orderBy('created_at', 'desc');

    return {
      totalCredits: credits[0]?.total || 0,
      recentActivity: transactions
    };
  }
}
