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

interface URLAddressProps {
  value: string;
}

export class URLAddress extends ValueObject<URLAddressProps> {
  static create(value: string): Result<URLAddress, Error> {
    const valueIsValid = URLAddress.validate(value);

    if (!valueIsValid.success) {
      return Result.fail(
        translateZodValidationError("URLAddress creation failed", valueIsValid.error)
      );
    }

    return Result.ok(new URLAddress({ value: valueIsValid.data }));
  }

  private static validate(value: string) {
    const schema = z.string().refine((value) => {
      const urlPattern = new RegExp(
        "^(https?:\\/\\/)?" + // protocolo opcional
          "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // nombre de dominio
          "((\\d{1,3}\\.){3}\\d{1,3}))" + // o dirección IP (v4)
          "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // puerto y ruta
          "(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
          "(\\#[-a-z\\d_]*)?$",
        "i" // fragment locator
      );
      return urlPattern.test(value);
    }, "Invalid URL format");

    return schema.safeParse(value);
  }

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

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

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