import { Result } from "@repo/rdx-utils";
import { z } from "zod/v4";
import { translateZodValidationError } from "../helpers";
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(
        translateZodValidationError("TINNumber creation failed", valueIsValid.error)
      );
    }
    return Result.ok(new TINNumber({ value: valueIsValid.data }));
  }

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

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

  toString() {
    return String(this.props.value);
  }
}
