import { afterEach, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { buildRouter } from "@wrnexus/router";
import { createHandlers, type RuntimeDeps } from "../src/runtime.ts";

const roots: string[] = [];
afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })));

test("plugin render lifecycle transforms final documents", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-plugin-render-"));
  roots.push(root);
  const app = join(root, "app");
  mkdirSync(join(app, "pages"), { recursive: true });
  writeFileSync(join(app, "pages/index.ts"), "export default () => '';\n");
  const handlers = createHandlers({
    mode: "development",
    hmr: false,
    router: buildRouter(app),
    loadModule: async () => ({ default: () => "<h1>Home</h1>" }),
    renderHtml: (html) => html.replace("</body>", "<!-- plugin-render --></body>"),
    getMiddleware: async () => [],
    assets: { serve: async () => null },
  } satisfies RuntimeDeps);
  const response = await handlers.fetch(new Request("https://example.test/"), {
    upgrade: () => false,
  });
  expect(await response?.text()).toContain("<!-- plugin-render -->");
});
