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 interface ITINNumberOptions extends IStringValueObjectOptions {}

export class TINNumber extends StringValueObject {
  private static readonly MIN_LENGTH = 2;
  private static readonly MAX_LENGTH = 10;

  protected static validate(
    value: UndefinedOr<string>,
    options: ITINNumberOptions
  ) {
    const rule = Joi.string()
      .allow(null)
      .allow("null")
      .allow("")
      .default("")
      .trim()
      .min(TINNumber.MIN_LENGTH)
      .max(TINNumber.MAX_LENGTH)

      .label(options.label ? options.label : "value");

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

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

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

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

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