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

export interface DisputeRouteRecord {
  id?: string;
  tenant_id: string;
  order_id: string;
  source_node_id: string;
  target_node_id: string;
  dispute_data_json: string;
  status: 'ROUTED' | 'ARBITRATING' | 'RESOLVED' | 'FAILED';
  arbitration_result?: string;
  created_at?: Date;
}

/**
 * [SOV_NET_04] 跨节点争议自动仲裁转发 (Global Dispute Router)
 * @description 支持在全球贸易节点间安全路由争议证据链，协同 AGI 进行跨节点仲裁。
 */
export class GlobalDisputeRouter {
  private static readonly DISPUTE_ROUTING_TABLE = 'cf_global_dispute_routes';

  /**
   * 路由争议证据到目标节点
   */
  static async routeDispute(tenantId: string, evidence: DisputeEvidence, targetNodeId: string) {
    logger.info(`[DisputeRouter] Routing dispute for order ${evidence.orderId} to node ${targetNodeId}`);

    // 1. 本地预审计 (联动 DisputeArbitrationService)
    const localAudit = await DisputeArbitrationService.analyzeDispute(tenantId, evidence);

    // 2. 创建路由记录
    const routeRecord: DisputeRouteRecord = {
      tenant_id: tenantId,
      order_id: evidence.orderId,
      source_node_id: 'LOCAL_HUB', // 假设当前节点 ID
      target_node_id: targetNodeId,
      dispute_data_json: JSON.stringify(evidence),
      status: 'ROUTED',
      created_at: new Date()
    };

    const [id] = await db(this.DISPUTE_ROUTING_TABLE).insert(routeRecord);
    
    logger.info(`[DisputeRouter] Dispute routed successfully, record ID: ${id}`);

    // 3. 模拟跨节点 RPC 调用传输数据
    // sendMessageToNode(targetNodeId, 'DISPUTE_SYNC', evidence);

    return { routeId: id, localAudit };
  }

  /**
   * 接收来自其它节点的争议请求并触发仲裁
   */
  static async handleIncomingDispute(tenantId: string, remoteDispute: DisputeRouteRecord) {
    logger.info(`[DisputeRouter] Handling incoming dispute for order ${remoteDispute.order_id} from node ${remoteDispute.source_node_id}`);

    const evidence: DisputeEvidence = JSON.parse(remoteDispute.dispute_data_json);

    // 触发本地 AGI 仲裁
    const arbitrationResult = await DisputeArbitrationService.analyzeDispute(tenantId, evidence);

    // 更新路由状态 (模拟同步回源节点)
    await db(this.DISPUTE_ROUTING_TABLE)
      .insert({
        ...remoteDispute,
        tenant_id: tenantId,
        status: 'RESOLVED',
        arbitration_result: JSON.stringify(arbitrationResult),
        updated_at: new Date()
      });

    return arbitrationResult;
  }

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