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

export interface CrossNodeSettlementRecord {
  id?: string;
  tenant_id: string;
  source_node_id: string;
  target_node_id: string;
  order_id: string;
  amount: number;
  currency: string;
  status: 'PENDING' | 'EXECUTED' | 'FAILED';
  settlement_proof_hash?: string;
  created_at?: Date;
}

/**
 * [SOV_NET_02] 跨节点自治清算协议实现 (Cross-Node Settlement)
 * @description 联动 DID Settlement 实现跨 Hub 节点间的自动化利润分润与清算。
 */
export class CrossNodeSettlementService {
  private static readonly CROSS_NODE_TABLE = 'cf_cross_node_settlements';

  /**
   * 发起跨节点清算请求
   */
  static async initiateCrossNodeSettlement(params: {
    tenantId: string;
    sourceNodeId: string;
    targetNodeId: string;
    orderId: string;
    amount: number;
    currency: string;
  }): Promise<CrossNodeSettlementRecord> {
    logger.info(`[CrossNodeSettlement] Initiating settlement for order ${params.orderId} from node ${params.sourceNodeId} to ${params.targetNodeId}`);

    // 1. 验证源节点与目标节点权限 (模拟)
    
    // 2. 联动 DIDSettlementService 生成本地结算存证
    // 假设在跨节点清算中，目标节点是一个 DID 身份持有者
    const localSettlement = await DIDSettlementService.settleOrder(params.tenantId, params.orderId);
    
    const record: CrossNodeSettlementRecord = {
      tenant_id: params.tenantId,
      source_node_id: params.sourceNodeId,
      target_node_id: params.targetNodeId,
      order_id: params.orderId,
      amount: params.amount,
      currency: params.currency,
      status: 'PENDING',
      created_at: new Date()
    };

    // 3. 存储跨节点结算记录
    const [id] = await db(this.CROSS_NODE_TABLE).insert(record);
    record.id = id.toString();

    // 4. 模拟发送清算指令给目标 Hub 节点
    logger.info(`[CrossNodeSettlement] Settlement request sent to remote node ${params.targetNodeId}`);

    return record;
  }

  /**
   * 确认跨节点清算完成
   */
  static async confirmSettlement(id: string, proofHash: string) {
    await db(this.CROSS_NODE_TABLE)
      .where({ id })
      .update({
        status: 'EXECUTED',
        settlement_proof_hash: proofHash,
        updated_at: new Date()
      });
    
    logger.info(`[CrossNodeSettlement] Settlement ${id} confirmed with proof ${proofHash}`);
  }

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