import { Maybe, Result } from "@rdx/utils";
import { z } from "zod";
import { ValueObject } from "./value-object";

interface INameProps {
  value: string;
}

export class Name extends ValueObject<INameProps> {
  private static readonly MAX_LENGTH = 255;

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

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

    if (!valueIsValid.success) {
      return Result.fail(new Error(valueIsValid.error.errors[0]?.message));
    }
    return Result.ok(new Name({ value }));
  }

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

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

  static generateAcronym(name: string): string {
    const words = name.split(" ").map((word) => word[0]?.toUpperCase());
    let acronym = words.join("");

    // Asegurarse de que tenga 4 caracteres, recortando o añadiendo letras
    if (acronym.length > 4) {
      acronym = acronym.slice(0, 4);
    } else if (acronym.length < 4) {
      acronym = acronym.padEnd(4, "X"); // Se completa con 'X' si es necesario
    }

    return acronym;
  }

  getAcronym(): string {
    return Name.generateAcronym(this.toString());
  }

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

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