import assert from "node:assert/strict";
import test from "node:test";
import { formatFailure, startCraftos, startServer } from "./harness.js";

const SECRET = "s3cr3t-canary";

test("hello with the wrong secret is rejected in-band (unauthorized)", async () => {
  const server = await startServer({ serverPassword: SECRET });
  const craftos = startCraftos("gateway-client.lua", {
    computerId: 7,
    computerLabel: "auth-bad",
    shellArgs: [server.baseUrl, "wrong-secret", "auth"],
  });
  try {
    const result = await craftos.done;
    assert.match(
      result.output,
      /__CLOUD_HELLO__ ok=false code=unauthorized/,
      formatFailure("expected hello ok=false code=unauthorized", result.output),
    );
  } finally {
    craftos.abort();
    await craftos.done.catch(() => undefined);
    await server.close();
  }
});

test("hello with the correct secret succeeds", async () => {
  const server = await startServer({ serverPassword: SECRET });
  const craftos = startCraftos("gateway-client.lua", {
    computerId: 7,
    computerLabel: "auth-ok",
    shellArgs: [server.baseUrl, SECRET, "auth"],
  });
  try {
    const result = await craftos.done;
    assert.match(
      result.output,
      /__CLOUD_HELLO__ ok=true/,
      formatFailure("expected hello ok=true", result.output),
    );
  } finally {
    craftos.abort();
    await craftos.done.catch(() => undefined);
    await server.close();
  }
});
