import { describe, expect, test } from "bun:test";
import { kubernetesWatchOneEventShellFunction } from "./kubernetes-watch";

function runWatch(command: string): { exitCode: number; stdout: string; stderr: string } {
  const script = `set -euo pipefail\n${kubernetesWatchOneEventShellFunction()}\nunidesk_watch_one_event bash -c ${JSON.stringify(command)}`;
  const result = Bun.spawnSync(["bash", "-c", script], { stdout: "pipe", stderr: "pipe" });
  return { exitCode: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString() };
}

describe("kubernetes watch one event shell helper", () => {
  test("returns the first change", () => {
    expect(runWatch("printf 'pipelinerun/run-1\\n'")).toEqual({ exitCode: 0, stdout: "pipelinerun/run-1\n", stderr: "" });
  });

  test("treats an empty successful request-timeout as no change", () => {
    expect(runWatch("exit 0")).toEqual({ exitCode: 0, stdout: "", stderr: "" });
  });

  test("accepts producer SIGPIPE after the first event", () => {
    const result = runWatch("trap 'exit 141' PIPE; while :; do printf 'event\\n' || exit 141; done");
    expect(result.exitCode).toBe(0);
    expect(result.stdout).toBe("event\n");
  });

  test("preserves authentication and API failures", () => {
    const result = runWatch("echo 'Unauthorized' >&2; exit 7");
    expect(result).toEqual({ exitCode: 7, stdout: "", stderr: "Unauthorized\n" });
  });
});
