import Joi from "joi";

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

export class TextValueObject extends StringValueObject {
  protected static validate(value: UndefinedOr<string>, options: IStringValueObjectOptions) {
    const rule = Joi.string()
      .allow(null)
      .allow("")
      .default("")
      .trim()
      .label(options.label ? options.label : "value");

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

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

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

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