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

interface CurrencyCodeProps {
  value: string;
}

/**
 * ISO 4217 Currency Codes
 */

export class CurrencyCode extends ValueObject<CurrencyCodeProps> {
  private static readonly MIN_LENGTH = 3;
  private static readonly MAX_LENGTH = 3;

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

    return schema.safeParse(value);
  }

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

    if (!valueIsValid.success) {
      return Result.fail(
        translateZodValidationError("CurrencyCode creation failed", valueIsValid.error)
      );
    }
    return Result.ok(new CurrencyCode({ 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);
  }
}
