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

export class UniqueID extends ValueObject<string> {
  static create(id?: string, generateOnEmpty = false): Result<UniqueID, Error> {
    if (!id || id?.trim() === "") {
      if (!generateOnEmpty) {
        return Result.fail(new Error("ID cannot be undefined or null"));
      }
      return UniqueID.generateNewID();
    }

    // biome-ignore lint/style/noNonNullAssertion: <explanation>
    const result = UniqueID.validate(id!);

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

  static generate(): Result<UniqueID, never> {
    return Result.ok(new UniqueID(uuidv4()));
  }

  static validate(id: string) {
    const schema = z.string().trim().uuid({ message: "Invalid UUID format" });
    return schema.safeParse(id);
  }

  static generateNewID(): Result<UniqueID, never> {
    return Result.ok(new UniqueID(uuidv4()));
  }

  getValue(): string {
    return this.props;
  }

  toString(): string {
    return this.getValue();
  }

  toPrimitive() {
    return this.getValue();
  }
}
