import { describe, it, expect } from "vitest";
import { z } from "zod";
import { InMemoryRealtimeBroadcaster } from "@/in-memory-realtime-broadcaster";
import { defineRealtimeChannel } from "@/realtime-channel";

const ch = defineRealtimeChannel(
  "a.b",
  z.object({ x: z.number() }).strict(),
  { scope: "public" },
);

describe("InMemoryRealtimeBroadcaster", () => {
  it("validates payload via the descriptor schema", async () => {
    const b = new InMemoryRealtimeBroadcaster();
    await expect(
      b.broadcast(ch, { x: "not a number" } as never),
    ).rejects.toThrow();
  });

  it("delivers to subscribers in order", async () => {
    const b = new InMemoryRealtimeBroadcaster();
    const got: number[] = [];
    b.subscribe(ch, async (p) => { got.push(p.x); });
    await b.broadcast(ch, { x: 1 });
    await b.broadcast(ch, { x: 2 });
    expect(got).toEqual([1, 2]);
  });

  it("does nothing when no subscribers", async () => {
    const b = new InMemoryRealtimeBroadcaster();
    await b.broadcast(ch, { x: 1 });
    // does not throw
  });
});
