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

const secret = process.env.WRNEXUS_RPC_SECRET;
const app = process.env.WRNEXUS_APP_NAME;
afterEach(() => {
  if (secret === undefined) delete process.env.WRNEXUS_RPC_SECRET;
  else process.env.WRNEXUS_RPC_SECRET = secret;
  if (app === undefined) delete process.env.WRNEXUS_APP_NAME;
  else process.env.WRNEXUS_APP_NAME = app;
});

test("subjectPubSub carries and verifies the publishing subject", async () => {
  process.env.WRNEXUS_RPC_SECRET = "test-rpc-secret-at-least-32-chars-long";
  process.env.WRNEXUS_APP_NAME = "orders";
  const bus = subjectPubSub(createPubSub());
  let seen: string | undefined;
  bus.subscribe<{ id: string }>("order:created", (message, _topic, subject) => {
    expect(message.id).toBe("o1");
    seen = subject?.subjectId;
  });
  await bus.publish({ user: { id: "u1" }, locals: {} } as never, "order:created", { id: "o1" });
  expect(seen).toBe("u1");
});
