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

interface ICustomerNumberProps {
  value: string;
}

export class CustomerNumber extends ValueObject<ICustomerNumberProps> {
  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(CustomerNumber.MAX_LENGTH, {
        message: `String must be at most ${CustomerNumber.MAX_LENGTH} characters long`,
      });
    return schema.safeParse(value);
  }

  static create(value: string) {
    const result = CustomerNumber.validate(value);

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

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

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

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