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

interface PostalCodeProps {
  value: string;
}

export class PostalCode extends ValueObject<PostalCodeProps> {
  private static readonly MIN_LENGTH = 5;
  private static readonly MAX_LENGTH = 5;

  protected static validate(value: string) {
    const schema = z
      .string()
      .trim()
      .regex(/^[0-9]+$/, {
        message: "PostalCode must contain only numbers",
      })
      .min(PostalCode.MIN_LENGTH, {
        message: `PostalCode must be at least ${PostalCode.MIN_LENGTH} characters long`,
      })
      .max(PostalCode.MAX_LENGTH, {
        message: `PostalCode must be at most ${PostalCode.MAX_LENGTH} characters long`,
      });

    return schema.safeParse(value);
  }

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

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

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

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

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