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

/**
 * [BIZ_TRADE_20] 去中心化物流履约验证共识 (Fulfillment Consensus)
 * 负责通过 IoT 传感器节点或第三方 DID 节点的数字签名，对物流关键节点（妥投、签收）进行去中心化共识验证
 */
export class FulfillmentConsensusService {
  /**
   * 登记节点验证事件
   */
  static async registerNodeEvent(
    orderId: string, 
    nodeId: string, 
    eventType: 'PICKUP' | 'TRANSIT' | 'DELIVERED', 
    signature: string,
    traceId: string
  ): Promise<void> {
    // 逻辑：通过 TraceId 获取租户 ID 并检查功能开关 (此处模拟租户检查)
    if (!(await FeatureGovernanceService.isEnabled('BIZ_TRADE_FULFILLMENT_CONSENSUS'))) {
      return;
    }

    // 1. 验证签名真实性 (模拟调用机密计算服务)
    const isValid = await this.verifySignature(nodeId, signature);
    if (!isValid) throw new Error('Invalid node signature');

    await db.transaction(async (trx) => {
      // 2. 记录共识事件
      await trx('cf_fulfillment_consensus').insert({
        order_id: orderId,
        node_id: nodeId,
        event_type: eventType,
        signature,
        event_time: db.fn.now()
      });

      // 3. 检查是否达到共识阈值 (例如 3 个独立节点确认即可标记为妥投)
      const consensusCount = await trx('cf_fulfillment_consensus')
        .where({ order_id: orderId, event_type: eventType })
        .count('* as count')
        .first();

      if (consensusCount && Number(consensusCount.count) >= 3) {
        await this.finalizeFulfillment(orderId, eventType, traceId, trx);
      }
    });
  }

  /**
   * 模拟签名验证
   */
  private static async verifySignature(nodeId: string, signature: string): Promise<boolean> {
    return signature.startsWith('SIG-') && nodeId.length > 5;
  }

  /**
   * 达成共识后更新订单状态
   */
  private static async finalizeFulfillment(orderId: string, eventType: string, traceId: string, trx: any): Promise<void> {
    if (eventType === 'DELIVERED') {
      await trx('cf_orders')
        .where({ id: orderId })
        .update({
          status: 'DELIVERED',
          updated_at: db.fn.now()
        });

      await AuditService.log({
        tenantId: 'SYSTEM', // 全局事件
        userId: 'SYSTEM_BOT',
        module: 'FULFILLMENT_CONSENSUS',
        action: 'FULFILLMENT_CONSENSUS_REACHED',
        resourceType: 'ORDER',
        resourceId: orderId,
        traceId: traceId,
        afterSnapshot: JSON.stringify({ status: 'DELIVERED' }),
        result: 'success',
        source: 'node',
        metadata: { reason: 'Multi-node consensus reached' }
      });
    }
  }

  /**
   * 获取某订单的共识链
   */
  static async getConsensusChain(orderId: string) {
    return await db('cf_fulfillment_consensus')
      .where({ order_id: orderId })
      .orderBy('event_time', 'asc');
  }
}
