// src/lib/backlink/domain-profile-import.ts — provider export → domain_backlinks insert rows.
import { createHash } from "node:crypto";
import * as wasm from "import-core";
import type { BacklinkSource } from "@/lib/backlink/types";
import type { domainBacklinks } from "@/lib/db/domain-schema";

type InsertRow = typeof domainBacklinks.$inferInsert;

interface RawDomainBacklink {
  sourceUrl: string;
  sourceTitle: string | null;
  sourceDomain: string;
  targetUrl: string;
  anchor: string | null;
  authority: number | null;
  nofollow: boolean;
  sponsored: boolean;
  ugc: boolean;
  sitewide: boolean;
  placement: string;
  firstSeen: string;
  lastSeen: string;
  isNew: boolean;
  isLost: boolean;
}

function coerceDate(s: string): Date | null {
  const t = s.trim();
  if (!t) return null;
  const d = new Date(t);
  return Number.isNaN(d.getTime()) ? null : d;
}

export function parseDomainBacklinks(
  csvText: string,
  siteId: string,
  importedAt: Date,
  source: BacklinkSource = "semrush",
): InsertRow[] {
  const raw = wasm.parse_domain_backlinks_csv(csvText) as RawDomainBacklink[];
  const seen = new Set<string>();
  const out: InsertRow[] = [];
  for (const r of raw) {
    const hash = createHash("sha1")
      .update(`${r.sourceUrl}|${r.targetUrl}`)
      .digest("hex")
      .slice(0, 24);
    // Source-scoped id: the same backlink from two providers is two rows.
    const id = `${siteId}:${source}:${hash}`;
    if (seen.has(id)) continue;
    seen.add(id);
    out.push({
      id,
      siteId,
      source,
      sourceUrl: r.sourceUrl,
      sourceTitle: r.sourceTitle,
      sourceDomain: r.sourceDomain,
      targetUrl: r.targetUrl,
      anchor: r.anchor,
      authority: r.authority,
      nofollow: r.nofollow,
      sponsored: r.sponsored,
      ugc: r.ugc,
      sitewide: r.sitewide,
      placement: r.placement,
      firstSeen: coerceDate(r.firstSeen),
      lastSeen: coerceDate(r.lastSeen),
      isNew: r.isNew,
      isLost: r.isLost,
      importedAt,
    });
  }
  return out;
}
