import Joi from "joi";

//import JoiPhoneNumber from "joi-phone-number";
import { UndefinedOr } from "../../../../utilities";
import { RuleValidator } from "../RuleValidator";
import { DomainError, handleDomainError } from "../errors";
import { Result } from "./Result";
import { IStringValueObjectOptions, StringValueObject } from "./StringValueObject";

export class Phone extends StringValueObject {
  protected static validate(value: UndefinedOr<string>, options: IStringValueObjectOptions) {
    const rule = Joi.string() //.extend(JoiPhoneNumber)
      .allow(null)
      .allow("")
      .trim()
      //.phoneNumber(/*{ defaultCountry: 'ES', format: 'national' }*/)
      .label(options.label ? options.label : "value");

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

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

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

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

  public format(/*countryCode: string*/) {
    const rule = Joi /*.extend(JoiPhoneNumber)*/.string();
    /*.phoneNumber({
        defaultCountry: countryCode,
        format: "international",
      })*/
    const validationResult = RuleValidator.validate(rule, this.value);

    return validationResult.isSuccess ? validationResult.object : validationResult.error.message;
  }
}

export class Phone_ValidationError extends Joi.ValidationError {}
