import '../utils/formatters.dart';

/// 交易信息
class TransactionInfo {
  final String hash;
  final int blockHeight;
  final String from;
  final String to;
  final BigInt value;
  final int gasUsed;
  final String status; // "success" | "failed"

  TransactionInfo({
    required this.hash,
    required this.blockHeight,
    required this.from,
    required this.to,
    required this.value,
    required this.gasUsed,
    required this.status,
  });

  /// 从 eth_getTransactionByHash + eth_getTransactionReceipt 合并解析
  factory TransactionInfo.fromRpcJson(
    Map<String, dynamic> txJson,
    Map<String, dynamic> receiptJson,
  ) {
    final statusHex = receiptJson['status'] as String;
    final statusVal = Formatters.hexToInt(statusHex);

    return TransactionInfo(
      hash: txJson['hash'] as String,
      blockHeight:
          Formatters.hexToInt(receiptJson['blockNumber'] as String),
      from: txJson['from'] as String,
      to: txJson['to'] as String? ?? '',
      value: Formatters.hexToBigInt(txJson['value'] as String),
      gasUsed: Formatters.hexToInt(receiptJson['gasUsed'] as String),
      status: statusVal == 1 ? 'success' : 'failed',
    );
  }

  factory TransactionInfo.fromJson(Map<String, dynamic> json) {
    return TransactionInfo(
      hash: json['hash'] as String,
      blockHeight: json['blockHeight'] as int,
      from: json['from'] as String,
      to: json['to'] as String,
      value: BigInt.parse(json['value'].toString()),
      gasUsed: json['gasUsed'] as int,
      status: json['status'] as String,
    );
  }

  Map<String, dynamic> toJson() => {
        'hash': hash,
        'blockHeight': blockHeight,
        'from': from,
        'to': to,
        'value': value.toString(),
        'gasUsed': gasUsed,
        'status': status,
      };

  bool get isSuccess => status == 'success';
}
