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

interface ICustomerInvoiceSerieProps {
  value: string;
}

export class CustomerInvoiceSerie extends ValueObject<ICustomerInvoiceSerieProps> {
  private static readonly MAX_LENGTH = 255;
  private static readonly FIELD = "invoiceSeries";
  private static readonly ERROR_CODE = "INVALID_INVOICE_SERIE";

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

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

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

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

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

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

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

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