/**
 * `wrnexus test [app-dir] [--watch] [--profile=test]` — run the app's test files
 * with `bun test`. Defaults to the `test` profile (config + .env.test). Extra
 * args after `--` (or bun test flags) pass straight through.
 */

import { spawn } from "node:child_process";
import { resolve } from "node:path";

export function runTests(appRoot: string, args: string[]): void {
  const root = resolve(appRoot);
  const watch = args.includes("--watch");
  const passthrough = args.filter(
    (a) => !a.startsWith("--profile=") && a !== "--watch" && a !== appRoot,
  );

  const child = spawn(
    process.execPath, // the Bun binary
    ["test", ...(watch ? ["--watch"] : []), ...passthrough],
    { stdio: "inherit", cwd: root },
  );
  child.on("exit", (code, signal) => {
    if (signal) return;
    process.exit(code ?? 0);
  });
}
