import { describe, expect, it } from "bun:test";
import { buildContentAnalysis } from "./analysis";

const comp = (over: Record<string, unknown>) => ({
  position: 1,
  domain: "d",
  url: "u",
  backlinks: null,
  refDomains: null,
  pageAuthority: null,
  searchTraffic: null,
  urlKeywords: null,
  title: null,
  metaDescription: null,
  lang: null,
  images: null,
  imagesWithoutAlt: null,
  imageAlts: null,
  missingAltSrcs: null,
  hasJsonLd: null,
  jsonLdTypes: null,
  crawledAt: null,
  ...over,
});

// biome-ignore lint/suspicious/noExplicitAny: test fixture
const snap = (over: Record<string, unknown> = {}): any => ({
  source: "se-ranking",
  importedAt: "x",
  features: ["People also ask"],
  competitors: [
    comp({ backlinks: 100, pageAuthority: 50, images: 10, hasJsonLd: true }),
    comp({ backlinks: 300, pageAuthority: 70, images: 20, hasJsonLd: false }),
  ],
  ...over,
});

// biome-ignore lint/suspicious/noExplicitAny: test fixture
const brief = (over: Record<string, unknown> = {}): any => ({
  source: "ytg",
  query: "",
  language: "",
  lang: "fr",
  country: "FR",
  importedAt: "",
  primaryIntent: "commercial",
  objectives: [],
  keySubjects: ["panneaux"],
  questions: ["q1", "q2"],
  tone: [],
  style: [],
  valueProps: [],
  topTerms: [],
  twoGrams: [],
  threeGrams: [],
  entities: ["EDF"],
  rawBrief: "",
  rawGuide: "",
  ...over,
});

describe("buildContentAnalysis", () => {
  it("derives serp ok + medians + features", () => {
    const a = buildContentAnalysis({ FR: snap() }, null, "FR");
    expect(a.serp.state).toBe("ok");
    expect(a.serp.count).toBe(2);
    expect(a.serp.medianBacklinks).toBe(200);
    expect(a.serp.medianAuthority).toBe(60);
    expect(a.serp.features).toContain("People also ask");
  });

  it("onpage ok when crawled (avgImages + jsonLdPct); partial otherwise", () => {
    const ok = buildContentAnalysis(
      { FR: snap({ crawledAt: "2026-06-08" }) },
      null,
      "FR",
    );
    expect(ok.onpage.state).toBe("ok");
    expect(ok.onpage.avgImages).toBe(15);
    expect(ok.onpage.jsonLdPct).toBe(50);
    const partial = buildContentAnalysis({ FR: snap() }, null, "FR");
    expect(partial.onpage.state).toBe("partial");
  });

  it("brief ok / other-locale / none", () => {
    const ok = buildContentAnalysis(null, { FR: brief() }, "FR").brief;
    expect(ok.state).toBe("ok");
    expect(ok.intent).toBe("commercial");
    expect(ok.questions).toBe(2);
    expect(ok.subjects).toContain("panneaux");
    expect(buildContentAnalysis(null, { US: brief() }, "FR").brief.state).toBe(
      "other-locale",
    );
    expect(buildContentAnalysis(null, {}, "FR").brief.state).toBe("none");
  });

  it("no keyword/locale → all none", () => {
    const a = buildContentAnalysis(null, null, null);
    expect(a.serp.state).toBe("none");
    expect(a.onpage.state).toBe("none");
    expect(a.brief.state).toBe("none");
  });
});
