import assert from "node:assert/strict";
import test from "node:test";

import { createCoreDiscoveryClient } from "../src/core-client.mjs";

const gatewayToken = "test-only-gateway-token-with-32-bytes";

test("posts a discovery through the authenticated internal Core boundary", async () => {
  let captured;
  const observe = createCoreDiscoveryClient({
    coreUrl: "http://device-control-core:18120",
    gatewayToken,
    fetchImpl: async (url, options) => {
      captured = { url, options };
      return new Response(JSON.stringify({
        ok: true,
        discovery: {
          lifecycleState: "quarantine",
          commandTransport: "disabled",
        },
      }), {
        status: 201,
        headers: { "Content-Type": "application/json" },
      });
    },
  });
  const signal = {
    schemaVersion: "nodedc.device.discovery-signal.v1",
    sessionRef: "session:test",
  };
  const discovery = await observe(signal);
  assert.equal(
    captured.url,
    "http://device-control-core:18120/internal/v1/device-discoveries:observe",
  );
  assert.equal(
    captured.options.headers.Authorization,
    `Bearer ${gatewayToken}`,
  );
  assert.deepEqual(JSON.parse(captured.options.body), signal);
  assert.equal(discovery.lifecycleState, "quarantine");
});

test("fails closed when Core does not return a quarantine view", async () => {
  const observe = createCoreDiscoveryClient({
    coreUrl: "http://device-control-core:18120",
    gatewayToken,
    fetchImpl: async () => new Response(JSON.stringify({
      ok: true,
      discovery: {
        lifecycleState: "claimed",
        commandTransport: "disabled",
      },
    }), { status: 200 }),
  });
  await assert.rejects(
    () => observe({ schemaVersion: "test" }),
    /device_gateway_core_ingest_contract_invalid/,
  );
});
