import assert from "node:assert/strict";
import { beforeEach, mock, test } from "bun:test";

import type { CommandResult } from "../command";

interface RunCommandCall {
  command: string[];
  cwd: string;
  options: { timeoutMs?: number; env?: NodeJS.ProcessEnv; input?: string };
}

const runCommandCalls: RunCommandCall[] = [];

mock.module("../command", () => ({
  runCommand(command: string[], cwd: string, options: RunCommandCall["options"] = {}): CommandResult {
    runCommandCalls.push({ command, cwd, options });
    return { command, cwd, exitCode: 0, stdout: "", stderr: "", signal: null, timedOut: false };
  },
  async runCommandObserved(command: string[], cwd: string): Promise<CommandResult> {
    return { command, cwd, exitCode: 0, stdout: "", stderr: "", signal: null, timedOut: false };
  },
  commandOk(): boolean {
    return true;
  },
  async runCommandToFiles(): Promise<number> {
    return 0;
  },
  tailFile(): string {
    return "";
  },
}));

const { runNodeHostScript } = await import("./runtime-common");

beforeEach(() => {
  runCommandCalls.length = 0;
});

test("node host scripts are sent through trans stdin instead of inline argv", () => {
  const script = "printf render-ok\\n";

  runNodeHostScript({ nodeRoute: "JD01" } as never, script, 55);

  assert.equal(runCommandCalls.length, 1);
  const call = runCommandCalls[0]!;
  assert.deepEqual(call.command.slice(-2), ["JD01", "sh"]);
  assert.equal(call.command.includes("--"), false);
  assert.equal(call.options.timeoutMs, 55_000);
  assert.equal(call.options.input, `${script}\n`);
});
