import {
  DomainError,
  IStringValueObjectOptions,
  Result,
  RuleValidator,
  StringValueObject,
  handleDomainError,
} from "@shared/contexts";
import { NullOr, UndefinedOr } from "@shared/utilities";
import Joi from "joi";
import { IDealer } from "../Dealer";

export interface IQuoteReferenceOptions extends IStringValueObjectOptions {}

export class QuoteReference extends StringValueObject {
  private static readonly MAX_LENGTH = 255;

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

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

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

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

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

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

  public static fromPrevious(
    previousReference: NullOr<QuoteReference>,
    dealer: IDealer
  ): Result<QuoteReference> {
    const lastNumber = previousReference
      ? QuoteReference._extractSequenceFromReference(previousReference)
      : 0;

    const newNumber = lastNumber + 1;
    const dealerAcronym = dealer.getAcronym();
    const newReference = `${dealerAcronym}-${newNumber.toString().padStart(4, "0")}`;

    return QuoteReference.create(newReference);
  }

  private static _extractSequenceFromReference(reference: QuoteReference): number {
    const parts = reference.toString().split("-");
    return parseInt(parts[parts.length - 1], 10);
  }
}
