import { ValueObject } from "@repo/rdx-ddd";
import { Result } from "@repo/rdx-utils";
import * as z from "zod/v4";

interface UsernameProps {
  value: string;
}

export class Username extends ValueObject<UsernameProps> {
  static create(username: string): Result<Username, Error> {
    const result = Username.validate(username);

    return result.success
      ? Result.ok(new Username({ value: result.data }))
      : Result.fail(new Error(result.error.errors[0].message));
  }

  private static validate(username: string) {
    const schema = z
      .string()
      .min(3, { message: "Username must be at least 3 characters long" })
      .max(30, { message: "Username cannot exceed 30 characters" })
      .regex(/^[a-zA-Z0-9_]+$/, {
        message: "Username can only contain letters, numbers, and underscores",
      });

    return schema.safeParse(username);
  }

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

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

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