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 class AddressType 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: "type",
      ...options,
    };

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

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

  public isBilling(): Boolean {
    return this.toString() === "billing";
  }

  public isShipping(): Boolean {
    return this.toString() === "shipping";
  }
}

export class AddressType_ValidationError extends Joi.ValidationError {}
