import Joi from "joi";
import { UndefinedOr } from "../../../../utilities";

import { DomainError, handleDomainError } from "../errors";
import { RuleValidator } from "../RuleValidator";
import { Result } from "./Result";
import { IStringValueObjectOptions, StringValueObject } from "./StringValueObject";

export class Slug extends StringValueObject {
  protected static readonly MIN_LENGTH = 2;
  protected static readonly MAX_LENGTH = 100;

  protected static validate(value: UndefinedOr<string>, options: IStringValueObjectOptions) {
    const rule = Joi.string()
      .allow(null)
      .allow("")
      .default("")
      .trim()
      .regex(/^[a-z0-9-]+$/)
      .min(Slug.MIN_LENGTH)
      .max(Slug.MAX_LENGTH)
      .label(options.label ? options.label : "value");

    return RuleValidator.validate<string>(rule, value);
    /*if (slug === undefined) {
      return Result.ok<string>("");
    }

    const _slug = String(slug);

    if (!_slug || _slug.trim().length < this.MIN_LENGTH) {
      return Result.fail<TooShortSlugError>(
        new TooShortSlugError(
          `Slug must be at least ${this.MIN_LENGTH} characters long.`,
        ),
      );
    }

    if (_slug.trim().length > this.MAX_LENGTH) {
      return Result.fail<TooLongSlugError>(
        new TooLongSlugError(
          `Slug must be at most ${this.MAX_LENGTH} characters long.`,
        ),
      );
    }

    // Implement your slug validation logic here
    // For example, you can check if it contains only lowercase letters, numbers, and hyphens
    const slugRegex = /^[a-z0-9-]+$/;
    if (!slugRegex.test(_slug)) {
      return Result.fail<InvalidSlugError>(
        new InvalidSlugError(`Invalid slug value`),
      );
    }

    return Result.ok<string>(_slug);
    */
  }

  private static sanitize(slug: string): string {
    return slug ? slug.trim() : "";
  }

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

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

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

    const slugValue = Slug.sanitize(validationResult.object);
    return Result.ok<Slug>(new Slug(slugValue));
  }
}

export class InvalidSlugError extends Error {}
export class TooShortSlugError extends Error {}
export class TooLongSlugError extends Error {}
