import { afterEach, describe, expect, test } from "bun:test";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { productionEntry, runPreview } from "../src/preview.ts";

const roots: string[] = [];
afterEach(async () =>
  Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))),
);

describe("production preview", () => {
  test("refuses to approximate a missing production build", () => {
    expect(() => productionEntry("missing-preview-root")).toThrow("WRN-PREVIEW-NO-BUILD");
  });

  test("executes the exact dist server with production environment", async () => {
    const root = join(tmpdir(), `wrnexus-preview-${crypto.randomUUID()}`);
    roots.push(root);
    await mkdir(join(root, "dist"), { recursive: true });
    await writeFile(
      join(root, "dist", "server.js"),
      "console.log(process.env.NODE_ENV + ':' + process.env.PORT)",
    );
    expect(productionEntry(root)).toBe(join(root, "dist", "server.js"));
    const child = runPreview(root, { port: 4100, stdio: "pipe" });
    const output = await new Response(child.stdout as never).text();
    expect(await new Promise<number | null>((resolve) => child.on("exit", resolve))).toBe(0);
    expect(output.trim()).toBe("production:4100");
  });
});
