import Joi from "joi";
import { UndefinedOr } from "../../../../utilities";
import { RuleValidator } from "../RuleValidator";
import { DomainError, handleDomainError } from "../errors";
import { Result } from "./Result";
import { IStringValueObjectOptions, StringValueObject } from "./StringValueObject";

export interface INameOptions extends IStringValueObjectOptions {}

export class Name extends StringValueObject {
  //private static readonly MIN_LENGTH = 1;
  private static readonly MAX_LENGTH = 100;

  protected static validate(value: UndefinedOr<string>, options: INameOptions) {
    const rule = Joi.string()
      .allow(null)
      .allow("")
      .default("")
      .trim()
      //.min(Name.MIN_LENGTH)
      .max(Name.MAX_LENGTH)
      .label(options.label ? options.label : "value");

    return RuleValidator.validate<string>(rule, value);
  }

  public static create(value: UndefinedOr<string>, options: INameOptions = {}) {
    const _options = {
      label: "name",
      ...options,
    };

    const validationResult = Name.validate(value, _options);

    if (validationResult.isFailure) {
      return Result.fail(
        handleDomainError(DomainError.INVALID_INPUT_DATA, validationResult.error.message, _options)
      );
    }

    return Result.ok(new Name(validationResult.object));
  }

  public 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;
  }

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