import { expect, test } from "bun:test";

import { createWorkbenchKafkaEventPublisher } from "./kafka-event-publisher.ts";

test("L0 publisher writes semantic activity to hwlab.event.v1", async () => {
  const sent: Array<Record<string, any>> = [];
  const publisher = createWorkbenchKafkaEventPublisher({
    env: kafkaEnvironment(),
    kafkaFactory: (() => ({
      producer() {
        return {
          async connect() {},
          async disconnect() {},
          async send(input: Record<string, any>) { sent.push(input); return [{ partition: 0, baseOffset: "7" }]; },
        };
      },
    })) as never,
    now: () => "2026-07-20T11:45:01.000Z",
  });

  await publisher.publish({
    traceId: "trc_l0_publish",
    sessionId: "ses_l0_publish",
    event: {
      type: "error",
      failureDomain: "infrastructure",
      component: "agentrun-manager",
      code: "connection-refused",
      failureKind: "connection-refused",
      retryPhase: "retryExhausted",
      retryable: true,
      attempt: 1,
      maxAttempts: 1,
      summary: "AgentRun 服务暂时不可达",
    },
  });
  await publisher.close?.();

  expect(sent).toHaveLength(1);
  expect(sent[0]?.topic).toBe("hwlab.event.v1");
  const envelope = JSON.parse(sent[0]?.messages[0].value);
  expect(envelope).toMatchObject({
    schema: "hwlab.event.v1",
    traceId: "trc_l0_publish",
    sessionId: "ses_l0_publish",
    event: {
      type: "error",
      status: "failed",
      failureDomain: "infrastructure",
      failureComponent: "agentrun-manager",
      failureCode: "connection-refused",
      retryPhase: "retryExhausted",
      retryAttempt: 1,
      retryMaxAttempts: 1,
      terminal: false,
      source: "hwlab.workbench.activity",
    },
  });
});

function kafkaEnvironment(): Record<string, string> {
  return {
    HWLAB_KAFKA_BOOTSTRAP_SERVERS: "127.0.0.1:9092",
    HWLAB_KAFKA_EVENT_TOPIC: "hwlab.event.v1",
    HWLAB_KAFKA_CLIENT_ID: "hwlab-workbench-l0",
  };
}
