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

/// 区块信息
class BlockInfo {
  final int height;
  final String hash;
  final DateTime timestamp;
  final int txCount;
  final String proposer;
  final BigInt gasUsed;
  final BigInt gasLimit;

  BlockInfo({
    required this.height,
    required this.hash,
    required this.timestamp,
    required this.txCount,
    required this.proposer,
    required this.gasUsed,
    required this.gasLimit,
  });

  /// 从 eth_getBlockByNumber RPC 结果解析
  factory BlockInfo.fromRpcJson(Map<String, dynamic> json) {
    final txs = json['transactions'];
    final txCount = txs is List ? txs.length : 0;

    return BlockInfo(
      height: Formatters.hexToInt(json['number'] as String),
      hash: json['hash'] as String,
      timestamp: DateTime.fromMillisecondsSinceEpoch(
        Formatters.hexToInt(json['timestamp'] as String) * 1000,
      ),
      txCount: txCount,
      proposer: json['miner'] as String,
      gasUsed: Formatters.hexToBigInt(json['gasUsed'] as String),
      gasLimit: Formatters.hexToBigInt(json['gasLimit'] as String),
    );
  }

  factory BlockInfo.fromJson(Map<String, dynamic> json) {
    return BlockInfo(
      height: json['height'] as int,
      hash: json['hash'] as String,
      timestamp: DateTime.parse(json['timestamp'] as String),
      txCount: json['txCount'] as int,
      proposer: json['proposer'] as String,
      gasUsed: BigInt.parse(json['gasUsed'].toString()),
      gasLimit: BigInt.parse(json['gasLimit'].toString()),
    );
  }

  Map<String, dynamic> toJson() => {
        'height': height,
        'hash': hash,
        'timestamp': timestamp.toIso8601String(),
        'txCount': txCount,
        'proposer': proposer,
        'gasUsed': gasUsed.toString(),
        'gasLimit': gasLimit.toString(),
      };
}
