import { DomainValidationError, ValueObject } from "@repo/rdx-ddd";
import { Maybe, Result } from "@repo/rdx-utils";
import { z } from "zod/v4";

interface CustomerInvoiceItemDescriptionProps {
  value: string;
}

export class CustomerInvoiceItemDescription extends ValueObject<CustomerInvoiceItemDescriptionProps> {
  private static readonly MAX_LENGTH = 255;
  private static readonly FIELD = "invoiceItemDescription";
  private static readonly ERROR_CODE = "INVALID_INVOICE_ITEM_DESCRIPTION";

  protected static validate(value: string) {
    const schema = z
      .string()
      .trim()
      .max(CustomerInvoiceItemDescription.MAX_LENGTH, {
        message: `Description must be at most ${CustomerInvoiceItemDescription.MAX_LENGTH} characters long`,
      });
    return schema.safeParse(value);
  }

  static create(value: string) {
    const valueIsValid = CustomerInvoiceItemDescription.validate(value);

    if (!valueIsValid.success) {
      const detail = valueIsValid.error.message;
      return Result.fail(
        new DomainValidationError(
          CustomerInvoiceItemDescription.ERROR_CODE,
          CustomerInvoiceItemDescription.FIELD,
          detail
        )
      );
    }
    return Result.ok(new CustomerInvoiceItemDescription({ value }));
  }

  static createNullable(value?: string): Result<Maybe<CustomerInvoiceItemDescription>, Error> {
    if (!value || value.trim() === "") {
      return Result.ok(Maybe.none<CustomerInvoiceItemDescription>());
    }

    return CustomerInvoiceItemDescription.create(value).map((value) => Maybe.some(value));
  }

  getProps(): string {
    return this.props.value;
  }

  toString() {
    return String(this.props.value);
  }

  toPrimitive() {
    return this.getProps();
  }
}
