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

interface ICustomerInvoiceNumberProps {
  value: string;
}

export class CustomerInvoiceNumber extends ValueObject<ICustomerInvoiceNumberProps> {
  private static readonly MAX_LENGTH = 255;
  private static readonly FIELD = "invoiceNumber";
  private static readonly ERROR_CODE = "INVALID_INVOICE_NUMBER";

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

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

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

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

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

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