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 { createTestPlan } from "../src/test.ts";

const roots: string[] = [];
afterEach(async () =>
  Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))),
);
async function fixture(): Promise<string> {
  const root = join(tmpdir(), `wrnexus-test-command-${crypto.randomUUID()}`);
  roots.push(root);
  await mkdir(join(root, "test", "component"), { recursive: true });
  await writeFile(join(root, "test", "math.unit.test.ts"), "export {};\n");
  await writeFile(join(root, "test", "component", "card.test.ts"), "export {};\n");
  await writeFile(join(root, "test", "home.a11y.test.ts"), "export {};\n");
  await writeFile(join(root, "package.json"), "{}");
  return root;
}
describe("test command planning", () => {
  test("discovers the requested Bun test level", async () => {
    const root = await fixture();
    expect(createTestPlan(root, ["unit"]).files).toHaveLength(1);
    expect(createTestPlan(root, ["component"]).files[0]).toContain("card.test.ts");
    expect(createTestPlan(root, ["accessibility"]).files[0]).toContain("a11y.test.ts");
  });
  test("delegates browser and visual suites to Playwright", async () => {
    const root = await fixture();
    await writeFile(join(root, "playwright.config.ts"), "export default {};\n");
    expect(createTestPlan(root, ["browser"]).args).toContain("playwright");
    expect(createTestPlan(root, ["visual"]).args).toContain("@visual");
    const matrix = createTestPlan(root, [
      "browser",
      "--browsers=chromium,firefox",
      "--shard=2/3",
      "--install-browsers",
    ]);
    expect(matrix.args).toContain("firefox");
    expect(matrix.args).toContain("--shard=2/3");
    expect(matrix.args).toContain("--reporter=line,html");
    expect(matrix.setup?.args).toEqual(["x", "playwright", "install", "chromium", "firefox"]);
  });
  test("deterministically shards convention-based suites", async () => {
    const root = await fixture();
    await writeFile(join(root, "test", "second.unit.test.ts"), "export {};\n");
    expect(createTestPlan(root, ["unit", "--shard=1/2"]).files).toHaveLength(1);
    expect(() => createTestPlan(root, ["unit", "--shard=3/2"])).toThrow("WRN-TEST-SHARD");
  });
  test("keeps the unfiltered legacy command", async () => {
    const plan = createTestPlan(await fixture(), ["--watch"]);
    expect(plan.level).toBeUndefined();
    expect(plan.args).toEqual(["test", "--watch"]);
  });
});
