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

export interface TraceabilityAction {
  tenantId: string;
  productId: string;
  orderId?: string;
  action: 'SOURCING' | 'PACKING' | 'SHIPPING' | 'DELIVERED';
  metadata?: any;
}

/**
 * [BIZ_TRADE_11] 基于区块链的供应链溯源服务
 * @description 实现关键节点存证，模拟与区块链（如 AntChain 或 Hyperledger）的交互
 */
export class TraceabilityService {
  private static readonly TABLE_NAME = 'cf_traceability_logs';

  /**
   * 记录关键节点并执行区块链存证 (BIZ_TRADE_11)
   */
  static async recordNode(params: TraceabilityAction): Promise<string> {
    logger.info(`[Traceability] Recording ${params.action} for Product: ${params.productId}`);

    // 1. 模拟调用区块链 API 获取交易哈希
    const txHash = await this.mockBlockchainNotarization(params);

    // 2. 持久化本地溯源日志
    await db(this.TABLE_NAME).insert({
      tenant_id: params.tenantId,
      product_id: params.productId,
      order_id: params.orderId,
      action: params.action,
      blockchain_tx_hash: txHash,
      metadata: JSON.stringify(params.metadata || {}),
      created_at: new Date(),
      updated_at: new Date()
    });

    return txHash;
  }

  /**
   * 验证溯源节点合法性
   */
  static async verifyNode(txHash: string): Promise<boolean> {
    logger.info(`[Traceability] Verifying node validity for TxHash: ${txHash}`);
    // 逻辑：在实际场景中会请求区块链浏览器 API 校验哈希是否存在且内容一致
    return txHash.startsWith('0x');
  }

  private static async mockBlockchainNotarization(params: TraceabilityAction): Promise<string> {
    // 模拟区块链异步确认过程
    return `0x${Math.random().toString(16).slice(2, 10)}${Date.now().toString(16)}`;
  }

  /**
   * 获取商品的完整溯源链路
   */
  static async getFullChain(productId: string, tenantId: string): Promise<any[]> {
    return await db(this.TABLE_NAME)
      .where({ product_id: productId, tenant_id: tenantId })
      .orderBy('created_at', 'asc');
  }
}
