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

import Joi from "joi";

export interface IPasswordOptions extends IStringValueObjectOptions {}

export class Password extends StringValueObject {
  private static readonly MIN_LENGTH = 4;
  private static readonly MAX_LENGTH = 255;

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

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

  public static createFromHashedTextPassword(
    value: UndefinedOr<string>,
    options: IPasswordOptions = {},
  ) {
    const _options = {
      label: "password",
      ...options,
    };

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

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

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

  public static createFromPlainTextPassword(
    value: UndefinedOr<string>,
    options: IPasswordOptions = {},
  ) {
    const _options = {
      label: "password",
      ...options,
    };

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

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

    return Result.ok(
      new Password(Password.hashPassword(validationResult.object)),
    );
  }

  public static hashPassword(plainTextPassword: string): string {
    return bCrypt.hashSync(plainTextPassword, 10);
  }

  public verifyPassword(plainTextPassword: string): boolean {
    return bCrypt.compareSync(plainTextPassword, this.value!);
  }
}
