import { MoneyValue, MoneyValueProps, Percentage, Quantity } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";

type ItemAmountProps = Pick<MoneyValueProps, "value" | "currency_code">;

export class ItemAmount extends MoneyValue {
  public static DEFAULT_SCALE = 4;

  static create({ value, currency_code }: ItemAmountProps) {
    const props = {
      value: Number(value),
      scale: ItemAmount.DEFAULT_SCALE,
      currency_code,
    };
    return Result.ok(new ItemAmount(props));
  }

  static zero(currency_code: string) {
    const props = {
      value: 0,
      currency_code,
    };
    return ItemAmount.create(props).data;
  }

  toObjectString() {
    return {
      value: String(this.value),
      scale: String(this.scale),
      currency_code: this.currencyCode,
    };
  }

  // Ensure fluent operations keep the subclass type
  convertScale(newScale: number) {
    const mv = super.convertScale(newScale);
    const p = mv.toPrimitive();
    return new ItemAmount({
      value: p.value,
      currency_code: p.currency_code,
      scale: ItemAmount.DEFAULT_SCALE,
    });
  }

  add(addend: MoneyValue) {
    const mv = super.add(addend);
    const p = mv.toPrimitive();
    return new ItemAmount({
      value: p.value,
      currency_code: p.currency_code,
      scale: ItemAmount.DEFAULT_SCALE,
    });
  }

  subtract(subtrahend: MoneyValue) {
    const mv = super.subtract(subtrahend);
    const p = mv.toPrimitive();
    return new ItemAmount({
      value: p.value,
      currency_code: p.currency_code,
      scale: ItemAmount.DEFAULT_SCALE,
    });
  }

  multiply(multiplier: number | Quantity) {
    const mv = super.multiply(multiplier);
    const p = mv.toPrimitive();

    const result = new ItemAmount({
      value: p.value,
      currency_code: p.currency_code,
      scale: ItemAmount.DEFAULT_SCALE,
    });

    return result;
  }

  divide(divisor: number | Quantity) {
    const mv = super.divide(divisor);
    const p = mv.toPrimitive();
    return new ItemAmount({
      value: p.value,
      currency_code: p.currency_code,
      scale: ItemAmount.DEFAULT_SCALE,
    });
  }

  percentage(percentage: number | Percentage) {
    const mv = super.percentage(percentage);
    const p = mv.toPrimitive();
    return new ItemAmount({
      value: p.value,
      currency_code: p.currency_code,
      scale: ItemAmount.DEFAULT_SCALE,
    });
  }
}
