import { expect, test } from "bun:test";
import { createPubSub, kafkaDriver, natsDriver } from "../src/index.ts";

test("NATS adapter serializes messages and maps namespace wildcards", async () => {
  let subscription = "";
  let receive: ((data: Uint8Array, subject: string) => void) | undefined;
  const bus = createPubSub(
    natsDriver({
      async publish(subject, data) {
        receive?.(data, subject);
      },
      subscribe(subject, handler) {
        subscription = subject;
        receive = handler;
        return () => {
          receive = undefined;
        };
      },
    }),
  );
  const values: unknown[] = [];
  bus.subscribe("room:*", (value) => {
    values.push(value);
  });
  await bus.publish("room:one", { online: 2 });
  expect(subscription).toBe("room:>");
  expect(values).toEqual([{ online: 2 }]);
});

test("Kafka adapter preserves topic and JSON payload contracts", async () => {
  let receive: ((value: string, topic: string) => void) | undefined;
  const bus = createPubSub(
    kafkaDriver({
      async publish(topic, value) {
        receive?.(value, topic);
      },
      subscribe(_pattern, handler) {
        receive = handler;
        return () => {
          receive = undefined;
        };
      },
    }),
  );
  let received = "";
  bus.subscribe("events", (value, topic) => {
    received = `${topic}:${(value as { id: number }).id}`;
  });
  await bus.publish("events", { id: 7 });
  expect(received).toBe("events:7");
});
