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

interface ICustomerSerieProps {
  value: string;
}

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

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

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

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

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

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

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

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