import Decimal from 'decimal.js';
import { ShareAmount } from './share-amount.vo';

/**
 * 价格值对象
 */
export class Price {
  private readonly _value: Decimal;

  constructor(value: Decimal | string | number) {
    if (value instanceof Decimal) {
      this._value = value;
    } else {
      this._value = new Decimal(value);
    }

    if (this._value.isNegative()) {
      throw new Error('Price cannot be negative');
    }
  }

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

  /**
   * 计算价格
   * price = sharePool / (totalShares - blackHole - circulationPool)
   */
  static calculate(
    sharePool: ShareAmount,
    totalShares: ShareAmount,
    blackHole: ShareAmount,
    circulationPool: ShareAmount,
  ): Price {
    const denominator = totalShares.value
      .minus(blackHole.value)
      .minus(circulationPool.value);

    if (denominator.isZero() || denominator.isNegative()) {
      throw new Error('Invalid price calculation: denominator is zero or negative');
    }

    return new Price(sharePool.value.dividedBy(denominator));
  }

  multiply(amount: ShareAmount): ShareAmount {
    return new ShareAmount(this._value.times(amount.value));
  }

  toFixed(decimals: number = 18): string {
    return this._value.toFixed(decimals);
  }

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

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

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