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

export class Description extends StringValueObject {
  protected static validate(value: UndefinedOr<string>, options: IStringValueObjectOptions) {
    const ruleIsEmpty = Joi.string()
      .optional()
      .allow(null)
      .allow("")
      .default("")
      .label(String(options.label));

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

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

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

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

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