import { Result } from "@repo/rdx-utils";
import { z } from "zod/v4";
import { translateZodValidationError } from "../helpers";
import { ValueObject } from "./value-object";

interface LanguageCodeProps {
  value: string;
}

/**
 * ISO 639-1 (2 letras)
 */

export class LanguageCode extends ValueObject<LanguageCodeProps> {
  private static readonly MIN_LENGTH = 2;
  private static readonly MAX_LENGTH = 2;

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

    return schema.safeParse(value);
  }

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

    if (!valueIsValid.success) {
      return Result.fail(
        translateZodValidationError("LanguageCode creation failed", valueIsValid.error)
      );
    }
    return Result.ok(new LanguageCode({ value: valueIsValid.data }));
  }

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

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

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

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