// src/lib/backlink/ahrefs-dr.ts — Ahrefs free Domain Rating endpoint (no API key).
import "server-only";

export type DrResult =
  | { ok: true; dr: number }
  | { ok: false; reason: "invalid" | "rate_limited" | "error" };

const ENDPOINT = "https://api.ahrefs.com/v3/public/domain-rating-free";

interface DrBody {
  domain_rating?: { domain_rating?: number };
}

/** Fetch one domain's DR. `fetchFn` is injectable for tests (default: global fetch). */
export async function fetchDomainRating(
  domainNorm: string,
  fetchFn: typeof fetch = fetch,
): Promise<DrResult> {
  const url = `${ENDPOINT}?target=${encodeURIComponent(domainNorm)}&output=json`;
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), 8000);
  try {
    const res = await fetchFn(url, { signal: ctrl.signal });
    if (res.status === 429) return { ok: false, reason: "rate_limited" };
    if (!res.ok) return { ok: false, reason: "error" };
    const body = (await res.json()) as DrBody;
    const raw = body?.domain_rating?.domain_rating;
    if (typeof raw !== "number" || Number.isNaN(raw)) {
      return { ok: false, reason: "invalid" };
    }
    return { ok: true, dr: Math.max(0, Math.min(100, Math.round(raw))) };
  } catch {
    return { ok: false, reason: "error" };
  } finally {
    clearTimeout(timer);
  }
}
