/**
 * Backlinks Summary
 * ──────────────────
 * Fetches domain authority and backlink metrics from the structural data provider.
 * Extracted from dataforseo-onpage.ts for modularity.
 *
 * Internal module — third-party names must not appear in user-facing contexts.
 */

import { AuditDataSourceError } from "../types";

const BASE = "https://api.dataforseo.com/v3";
const LOGIN = process.env.DATAFORSEO_LOGIN ?? "";
const PASSWORD = process.env.DATAFORSEO_PASSWORD ?? "";

function authHeader(): string {
  return "Basic " + Buffer.from(`${LOGIN}:${PASSWORD}`).toString("base64");
}

function isConfigured(): boolean {
  return !!(LOGIN && PASSWORD);
}

async function dfsPost<T = unknown>(endpoint: string, body: unknown[]): Promise<T> {
  if (!isConfigured()) throw new AuditDataSourceError("Structural scanner not configured", "dataforseo-backlinks");

  const res = await fetch(`${BASE}${endpoint}`, {
    method: "POST",
    headers: { Authorization: authHeader(), "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });

  if (!res.ok) {
    throw new AuditDataSourceError(`Structural scanner HTTP ${res.status}`, "dataforseo-backlinks");
  }

  const data = (await res.json()) as { status_code?: number; status_message?: string; tasks?: unknown[] };
  if (data.status_code !== 20000) {
    throw new AuditDataSourceError(
      `Structural scanner envelope error ${data.status_code}`,
      "dataforseo-backlinks",
    );
  }
  return data as T;
}

export interface BacklinksSummary {
  domainRank: number | null;
  totalBacklinks: number | null;
  referringDomains: number | null;
  // Extended fields (null if not in API response):
  spamScore: number | null;
  brokenBacklinks: number | null;
}

export async function fetchBacklinksSummary(domain: string): Promise<BacklinksSummary> {
  const empty: BacklinksSummary = {
    domainRank: null,
    totalBacklinks: null,
    referringDomains: null,
    spamScore: null,
    brokenBacklinks: null,
  };
  if (!isConfigured()) return empty;

  try {
    const res = await dfsPost<{
      status_code: number;
      tasks?: Array<{
        result?: Array<{
          rank?: number;
          backlinks?: number;
          referring_domains?: number;
          spam_score?: number;
          broken_backlinks?: number;
        }>;
      }>;
    }>("/backlinks/summary/live", [{ target: domain, include_subdomains: true }]);

    const result = res.tasks?.[0]?.result?.[0];
    return {
      domainRank: result?.rank ?? null,
      totalBacklinks: result?.backlinks ?? null,
      referringDomains: result?.referring_domains ?? null,
      spamScore: result?.spam_score ?? null,
      brokenBacklinks: result?.broken_backlinks ?? null,
    };
  } catch (err) {
    console.warn(
      `[audit-backlinks] fetchBacklinksSummary failed for ${domain}:`,
      err instanceof Error ? err.message : err,
    );
    return empty;
  }
}
