import { ArticleIdentifier } from "@/contexts/catalog/domain";
import {
  Description,
  Entity,
  IDomainError,
  IEntityProps,
  MoneyValue,
  Percentage,
  Quantity,
  Result,
  UniqueID,
} from "@shared/contexts";

export interface IQuoteItemProps extends IEntityProps {
  idArticle: ArticleIdentifier;
  description: Description; // Descripción del artículo o servicio
  quantity: Quantity; // Cantidad de unidades
  unitPrice: MoneyValue; // Precio unitario en la moneda de la factura
  // subtotalPrice: MoneyValue; // Precio unitario * Cantidad
  discount: Percentage; // % descuento
  // totalPrice: MoneyValue;
}

export interface IQuoteItem {
  idArticle: ArticleIdentifier;
  description: Description;
  quantity: Quantity;
  unitPrice: MoneyValue;
  subtotalPrice: MoneyValue;
  discount: Percentage;
  totalPrice: MoneyValue;
}

export class QuoteItem extends Entity<IQuoteItemProps> implements IQuoteItem {
  public static create(props: IQuoteItemProps, id?: UniqueID): Result<QuoteItem, IDomainError> {
    return Result.ok(new QuoteItem(props, id));
  }

  get idArticle(): ArticleIdentifier {
    return this.props.idArticle;
  }

  get description(): Description {
    return this.props.description;
  }

  get quantity(): Quantity {
    return this.props.quantity;
  }

  get unitPrice(): MoneyValue {
    return this.props.unitPrice;
  }

  get subtotalPrice(): MoneyValue {
    return this.quantity.isNull() || this.unitPrice.isNull()
      ? MoneyValue.create({ amount: null, scale: 2 }).object
      : this.unitPrice.multiply(this.quantity.toNumber());
  }

  get discount(): Percentage {
    return this.props.discount;
  }

  get totalPrice(): MoneyValue {
    return this.subtotalPrice.isNull()
      ? MoneyValue.create({ amount: null, scale: 2 }).object
      : this.subtotalPrice.subtract(this.subtotalPrice.percentage(this.discount.toNumber()));
  }
}
