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

// Exercises the gateway -> computer direction: the gateway sends a `ping`
// server_request and the real libcloud client answers with a computer_response.
test("gateway->computer reverse ping is answered by the client", async () => {
  const server = await startServer();
  const craftos = startCraftos("gateway-client.lua", {
    computerId: 7,
    computerLabel: "ping",
    shellArgs: [server.baseUrl, "-", "idle"],
  });
  try {
    await waitFor(() => server.registry.has("global", "7:ping"), 12_000, "computer registered");
    const payload = await server.registry.request("global", "7:ping", "ping");
    assert.deepEqual(payload, { traposId: "7:ping" });
  } catch (error) {
    throw new Error(
      formatFailure(error instanceof Error ? error.message : String(error), craftos.snapshot()),
      { cause: error },
    );
  } finally {
    craftos.abort();
    await craftos.done.catch(() => undefined);
    await server.close();
  }
});
