import { afterAll, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { runBuild } from "../src/build.ts";

const scratchRoot = join(import.meta.dir, ".tmp-css-delivery");
mkdirSync(scratchRoot, { recursive: true });
afterAll(() => rmSync(scratchRoot, { recursive: true, force: true }));

test("production ships active themes separately and retains one component style copy", async () => {
  const root = mkdtempSync(join(scratchRoot, "app-"));
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  mkdirSync(join(root, "app", "components"), { recursive: true });
  mkdirSync(join(root, "app", "styles"), { recursive: true });
  writeFileSync(join(root, "package.json"), JSON.stringify({ name: "css-delivery-fixture" }));
  writeFileSync(
    join(root, "wrnexus.config.ts"),
    `export default { theme: { default: "dark", palette: "violet" }, styles: { entry: "app/styles/global.css" } };\n`,
  );
  writeFileSync(join(root, "app", "styles", "global.css"), ".app-shell{display:block}\n");
  writeFileSync(
    join(root, "app", "components", "Probe.wrn"),
    `component Probe { style { .unique-server-style-marker{color:red} } view { <p class="unique-server-style-marker">Probe</p> } }\n`,
  );
  writeFileSync(
    join(root, "app", "pages", "index.wrn"),
    `import Probe from "../components/Probe.wrn"\npage Home { view { <main class="app-shell"><Probe /></main> } }\n`,
  );

  await runBuild(root);
  const styles = readFileSync(join(root, "dist", "styles.css"), "utf8");
  const activeTheme = readFileSync(join(root, "dist", "theme", "dark", "violet.css"), "utf8");
  const server = readFileSync(join(root, "dist", "server.js"), "utf8");
  expect(styles).toContain(".app-shell");
  expect(styles).not.toContain("[data-theme=");
  expect(activeTheme.length).toBeLessThan(10_000);
  expect(server.match(/unique-server-style-marker/g)).toHaveLength(2);
});
