import Decimal from 'decimal.js';

export class Money {
  private readonly _value: Decimal;

  constructor(value: Decimal | string | number) {
    this._value = value instanceof Decimal ? value : new Decimal(value);
    if (this._value.isNegative()) {
      throw new Error('Money cannot be negative');
    }
  }

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

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

  subtract(other: Money): Money {
    const result = this._value.minus(other._value);
    if (result.isNegative()) {
      throw new Error('Insufficient balance');
    }
    return new Money(result);
  }

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

  divide(divisor: Decimal | string | number): Money {
    return new Money(this._value.dividedBy(divisor));
  }

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

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

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

  isGreaterThanOrEqual(other: Money): boolean {
    return this._value.greaterThanOrEqualTo(other._value);
  }

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

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

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

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