import {
  DomainError,
  IStringValueObjectOptions,
  Result,
  RuleValidator,
  StringValueObject,
  handleDomainError,
} from "@shared/contexts";
import { UndefinedOr } from "@shared/utilities";
import Joi from "joi";

export interface IQuoteCustomerReferenceOptions extends IStringValueObjectOptions {}

export class QuoteCustomerReference extends StringValueObject {
  private static readonly MAX_LENGTH = 255;

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

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

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

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

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

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