import { Maybe, Result } from "@repo/rdx-utils";
import { z } from "zod";
import { ValueObject } from "./value-object";

interface TINNumberProps {
  value: string;
}

export class TINNumber extends ValueObject<TINNumberProps> {
  private static readonly MIN_LENGTH = 2;
  private static readonly MAX_LENGTH = 10;

  protected static validate(value: string) {
    const schema = z
      .string()
      .trim()
      .min(TINNumber.MIN_LENGTH, {
        message: `TIN must be at least ${TINNumber.MIN_LENGTH} characters long`,
      })
      .max(TINNumber.MAX_LENGTH, {
        message: `TIN must be at most ${TINNumber.MAX_LENGTH} characters long`,
      });

    return schema.safeParse(value);
  }

  static create(value: string): Result<TINNumber, Error> {
    const valueIsValid = TINNumber.validate(value);

    if (!valueIsValid.success) {
      return Result.fail(new Error(valueIsValid.error.errors[0].message));
    }
    return Result.ok(new TINNumber({ value: valueIsValid.data }));
  }

  static createNullable(value?: string): Result<Maybe<TINNumber>, Error> {
    if (!value || value.trim() === "") {
      return Result.ok(Maybe.none<TINNumber>());
    }

    return TINNumber.create(value).map((value) => Maybe.some(value));
  }

  getValue(): string {
    return this.props.value;
  }

  toPrimitive(): string {
    return this.props.value;
  }
}
