export type UrlValidationResult = {
  ok: true;
  normalizedUrl: URL;
} | {
  ok: false;
  error: string;
};

export class UrlValidatorService {
  validateAndNormalize(rawUrl: string): UrlValidationResult {
    const trimmedUrl = (rawUrl || "").trim();
    if (!trimmedUrl) {
      return { ok: false, error: "Website URL is required" };
    }

    const normalizedInput = this.ensureProtocol(trimmedUrl);

    let url: URL;
    try {
      url = new URL(normalizedInput);
    } catch {
      return { ok: false, error: "Please enter a valid website URL" };
    }

    if (!["http:", "https:"].includes(url.protocol)) {
      return { ok: false, error: "Only http and https URLs are supported" };
    }

    if (!url.hostname) {
      return { ok: false, error: "Please enter a valid website URL" };
    }

    if (this.isPrivateOrLocalAddress(url.hostname)) {
      return { ok: false, error: "Private or local URLs are not allowed" };
    }

    return { ok: true, normalizedUrl: url };
  }

  private ensureProtocol(value: string): string {
    if (/^[a-z][a-z\d+\-.]*:\/\//i.test(value)) {
      return value;
    }

    return `https://${value}`;
  }

  private isPrivateOrLocalAddress(hostname: string): boolean {
    const lower = hostname.toLowerCase();

    if (lower === "localhost" || lower.endsWith(".localhost")) {
      return true;
    }

    if (lower === "::1") {
      return true;
    }

    if (/^\d{1,3}(\.\d{1,3}){3}$/.test(lower)) {
      return this.isPrivateIpv4(lower);
    }

    return false;
  }

  private isPrivateIpv4(ip: string): boolean {
    const parts = ip.split(".").map((segment) => Number(segment));
    if (parts.some((part) => Number.isNaN(part) || part < 0 || part > 255)) {
      return true;
    }

    const [a, b] = parts;

    if (a === 10) return true;
    if (a === 127) return true;
    if (a === 169 && b === 254) return true;
    if (a === 172 && b >= 16 && b <= 31) return true;
    if (a === 192 && b === 168) return true;
    if (a === 0) return true;

    return false;
  }
}
