/**
 * 区块号值对象
 */
export class BlockNumber {
  private readonly _value: bigint;

  private constructor(value: bigint) {
    this._value = value;
  }

  static create(value: bigint | number | string): BlockNumber {
    const num = BigInt(value);
    if (num < 0n) {
      throw new Error(`Block number cannot be negative: ${value}`);
    }
    return new BlockNumber(num);
  }

  get value(): bigint {
    return this._value;
  }

  get asNumber(): number {
    return Number(this._value);
  }

  equals(other: BlockNumber): boolean {
    return this._value === other._value;
  }

  isGreaterThan(other: BlockNumber): boolean {
    return this._value > other._value;
  }

  isLessThan(other: BlockNumber): boolean {
    return this._value < other._value;
  }

  add(blocks: number): BlockNumber {
    return new BlockNumber(this._value + BigInt(blocks));
  }

  subtract(blocks: number): BlockNumber {
    const result = this._value - BigInt(blocks);
    if (result < 0n) {
      throw new Error('Block number cannot be negative');
    }
    return new BlockNumber(result);
  }

  /**
   * 计算与另一个区块的差距
   */
  diff(other: BlockNumber): bigint {
    return this._value - other._value;
  }

  toString(): string {
    return this._value.toString();
  }
}
