import Decimal from 'decimal.js';

/**
 * 贡献值/算力金额值对象
 * 使用 Decimal.js 保证高精度计算
 */
export class ContributionAmount {
  private readonly _value: Decimal;

  constructor(value: Decimal | string | number) {
    this._value = new Decimal(value);
    if (this._value.isNaN()) {
      throw new Error('ContributionAmount must be a valid number');
    }
    if (this._value.isNegative()) {
      throw new Error('ContributionAmount cannot be negative');
    }
  }

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

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

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

  subtract(other: ContributionAmount): ContributionAmount {
    const result = this._value.minus(other._value);
    if (result.isNegative()) {
      throw new Error('ContributionAmount cannot be negative after subtraction');
    }
    return new ContributionAmount(result);
  }

  multiply(rate: Decimal | string | number): ContributionAmount {
    return new ContributionAmount(this._value.times(new Decimal(rate)));
  }

  divide(divisor: Decimal | string | number): ContributionAmount {
    const d = new Decimal(divisor);
    if (d.isZero()) {
      throw new Error('Cannot divide by zero');
    }
    return new ContributionAmount(this._value.dividedBy(d));
  }

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

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

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

  toString(decimalPlaces: number = 10): string {
    return this._value.toFixed(decimalPlaces);
  }

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

  static zero(): ContributionAmount {
    return new ContributionAmount(0);
  }

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