import { expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { invalidateModule, loadModule, setCompileCacheDir } from "../src/pipeline.ts";

test("invalidateModule loads changed server modules without restarting the process", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-hmr-"));
  const file = join(root, "page.ts");
  setCompileCacheDir(join(root, ".wrnexus"));

  try {
    writeFileSync(file, "export const value = 1;\n");
    expect((await loadModule(file)).value).toBe(1);

    writeFileSync(file, "export const value = 2;\n");
    expect((await loadModule(file)).value).toBe(1);

    invalidateModule(file);
    expect((await loadModule(file)).value).toBe(2);
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});

test("invalidateModule recompiles changed WRN files in-process", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-hmr-"));
  const file = join(root, "page.wrn");
  setCompileCacheDir(join(root, ".wrnexus"));

  try {
    writeFileSync(file, "page Home { view { <h1>First</h1> } }\n");
    const first = (await loadModule(file)).default as (ctx: unknown) => unknown;
    expect(String(first({}))).toContain("First");

    writeFileSync(file, "page Home { view { <h1>Second</h1> } }\n");
    invalidateModule(file);
    const second = (await loadModule(file)).default as (ctx: unknown) => unknown;
    expect(String(second({}))).toContain("Second");
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});
