import { expect, test } from "bun:test";
import {
  contentfulAdapter,
  createIncrementalHighlighter,
  renderMdxComponents,
  sanityAdapter,
  strapiAdapter,
} from "../src/index.ts";

test("MDX executes only explicitly registered bounded components", () => {
  const html = renderMdxComponents(`<Callout tone="info">Safe</Callout>`, {
    Callout: (props, children) => `<aside class="${props.tone}">${children}</aside>`,
  });
  expect(html).toBe(`<aside class="info">Safe</aside>`);
  expect(() => renderMdxComponents(`<Unknown />`, {})).toThrow("not registered");
});

test("syntax language bundles load once and only when encountered", async () => {
  let loads = 0;
  const highlighter = createIncrementalHighlighter({
    ts: async () => {
      loads++;
      return { highlight: (source) => `<mark>${source}</mark>` };
    },
  });
  expect(highlighter.languages()).toEqual([]);
  const html = await highlighter.render(`<pre><code class="language-ts">const x = 1;</code></pre>`);
  expect(html).toContain("<mark>const x = 1;</mark>");
  await highlighter.highlight("ts", "again");
  expect(loads).toBe(1);
});

test("vendor adapters construct encoded authenticated requests and normalize records", async () => {
  const urls: string[] = [];
  const fetcher = async (input: RequestInfo | URL) => {
    urls.push(String(input));
    return Response.json({
      items: [{ sys: { id: "c1" }, fields: { body: "Contentful" } }],
      result: [{ _id: "s1", body: "Sanity" }],
      data: [{ id: "t1", body: "Strapi" }],
    });
  };
  expect((await contentfulAdapter("space", "master", { fetch: fetcher }).list("post"))[0]?.id).toBe(
    "c1",
  );
  expect((await sanityAdapter("project", "dataset", { fetch: fetcher }).list("post"))[0]?.id).toBe(
    "s1",
  );
  expect((await strapiAdapter("https://cms.test", { fetch: fetcher }).list("posts"))[0]?.id).toBe(
    "t1",
  );
  expect(urls.every((url) => url.startsWith("https://"))).toBeTrue();
});
