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

export interface IQuoteCustomerOptions extends IStringValueObjectOptions {}

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

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

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

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

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

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

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