import { afterEach, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { runPluginCliCommand } from "../src/plugin-command.ts";

const roots: string[] = [];
afterEach(() => {
  for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
  delete (globalThis as Record<string, unknown>).__pluginCommandArgs;
});

test("application plugins can register executable CLI commands", async () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-plugin-command-"));
  roots.push(root);
  writeFileSync(
    join(root, "wrnexus.config.ts"),
    `export default {
      plugins: [{
        name: "command-test",
        cliCommands: [{
          name: "greet",
          run(args) { globalThis.__pluginCommandArgs = args }
        }]
      }]
    };
`,
  );
  expect(await runPluginCliCommand(root, "greet", ["Ada"])).toBe(true);
  expect((globalThis as Record<string, unknown>).__pluginCommandArgs).toEqual(["Ada"]);
  expect(await runPluginCliCommand(root, "missing", [])).toBe(false);
});
