import Decimal from 'decimal.js';
import { DomainError } from '@/shared/exceptions/domain.exception';

export class Hashpower {
  private readonly _value: Decimal;

  private constructor(value: Decimal) {
    if (value.lessThan(0)) {
      throw new DomainError('Hashpower cannot be negative');
    }
    this._value = value;
  }

  static create(value: number | string | Decimal): Hashpower {
    return new Hashpower(new Decimal(value));
  }

  static zero(): Hashpower {
    return new Hashpower(new Decimal(0));
  }

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

  get decimal(): Decimal {
    return this._value;
  }

  add(other: Hashpower): Hashpower {
    return new Hashpower(this._value.plus(other._value));
  }

  subtract(other: Hashpower): Hashpower {
    const result = this._value.minus(other._value);
    if (result.lessThan(0)) {
      throw new DomainError('Insufficient hashpower');
    }
    return new Hashpower(result);
  }

  isZero(): boolean {
    return this._value.isZero();
  }

  isPositive(): boolean {
    return this._value.greaterThan(0);
  }

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

  lessThan(other: Hashpower): boolean {
    return this._value.lessThan(other._value);
  }

  greaterThan(other: Hashpower): boolean {
    return this._value.greaterThan(other._value);
  }

  toString(): string {
    return `${this._value.toFixed(8)} HP`;
  }
}
