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 { CacheCoordinator } from "@wrnexus/cache";
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("declarative route policies cache loader data and expose inspection", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-cache-runtime-"));
  roots.push(root);
  const app = join(root, "app");
  mkdirSync(join(app, "pages"), { recursive: true });
  writeFileSync(join(app, "pages/dashboard.ts"), "export default () => '';\n");
  let loads = 0;
  const cache = new CacheCoordinator();
  const handlers = createHandlers({
    mode: "development",
    hmr: false,
    router: buildRouter(app),
    cache,
    loadModule: async () => ({
      __wrnexusCache: {
        strategy: "stale-while-revalidate",
        ttl: "5m",
        tags: '["dashboard"]',
        vary: '["language"]',
      },
      __wrnexusLoad: async () => ({ count: ++loads }),
      default: (ctx: { count: number }) => `<p>${ctx.count}</p>`,
    }),
    getMiddleware: async () => [],
    assets: { serve: async () => null },
  } satisfies RuntimeDeps);
  const server = { upgrade: () => false };
  const first = await handlers.fetch(new Request("https://example.test/dashboard"), server);
  const second = await handlers.fetch(new Request("https://example.test/dashboard"), server);
  expect(first?.headers.get("x-wrnexus-data-cache")).toBe("MISS");
  expect(second?.headers.get("x-wrnexus-data-cache")).toBe("HIT");
  expect(loads).toBe(1);
  const inspection = await handlers.fetch(
    new Request("https://example.test/__wrnexus/cache"),
    server,
  );
  expect((await inspection?.json())?.layers.data).toHaveLength(1);
});

test("safe full-page policies reuse static documents", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-page-cache-runtime-"));
  roots.push(root);
  const app = join(root, "app");
  mkdirSync(join(app, "pages"), { recursive: true });
  writeFileSync(join(app, "pages/marketing.ts"), "export default () => '';\n");
  let renders = 0;
  const pageCache = new CacheCoordinator();
  const handlers = createHandlers({
    mode: "production",
    hmr: false,
    router: buildRouter(app),
    cache: pageCache,
    loadModule: async () => ({
      __wrnexusCache: { scope: "page", strategy: "fresh", ttl: "5m", tags: '["marketing"]' },
      default: () => `<h1>Render ${++renders}</h1>`,
    }),
    getMiddleware: async () => [],
    assets: { serve: async () => null },
  } satisfies RuntimeDeps);
  const server = { upgrade: () => false };
  const first = await handlers.fetch(new Request("https://example.test/marketing"), server);
  const second = await handlers.fetch(new Request("https://example.test/marketing"), server);
  expect(first?.headers.get("x-wrnexus-page-cache")).toBe("MISS");
  expect(pageCache.inspect().layers.page).toHaveLength(1);
  expect(second?.headers.get("x-wrnexus-page-cache")).toBe("HIT");
  const firstHtml = await first!.text();
  const secondHtml = await second!.text();
  expect(secondHtml).toContain("Render 1");
  expect(/nonce="([^"]+)"/.exec(firstHtml)?.[1]).not.toBe(/nonce="([^"]+)"/.exec(secondHtml)?.[1]);
  expect(renders).toBe(1);
});

test("full-page cache refuses CSRF-bearing documents", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-page-cache-csrf-"));
  roots.push(root);
  const app = join(root, "app");
  mkdirSync(join(app, "pages"), { recursive: true });
  writeFileSync(join(app, "pages/account.ts"), "export default () => '';\n");
  let renders = 0;
  const cache = new CacheCoordinator();
  const handlers = createHandlers({
    mode: "production",
    hmr: false,
    router: buildRouter(app),
    cache,
    loadModule: async () => ({
      __wrnexusCache: { scope: "page", strategy: "fresh", ttl: "5m" },
      default: () =>
        `<form method="post" data-wrn-action="save"><button>${++renders}</button></form>`,
    }),
    getMiddleware: async () => [],
    assets: { serve: async () => null },
  } satisfies RuntimeDeps);
  const server = { upgrade: () => false };
  await handlers.fetch(new Request("https://example.test/account"), server);
  await handlers.fetch(new Request("https://example.test/account"), server);
  expect(renders).toBe(2);
  expect(cache.inspect().layers.page).toEqual([]);
});
