import assert from "node:assert/strict";
import test from "node:test";
import { ActiveSseStream, type SseStreamEvent } from "../src/active-streams.js";

test("ActiveSseStream replays buffered events to late subscribers", () => {
  const stream = new ActiveSseStream();
  stream.emit("delta", { text: "hel" });
  stream.emit("delta", { text: "lo" });

  const events: SseStreamEvent[] = [];
  const unsubscribe = stream.subscribe((event) => events.push(event));
  unsubscribe();

  assert.deepEqual(events, [
    { event: "delta", data: { text: "hel" } },
    { event: "delta", data: { text: "lo" } },
  ]);
});

test("ActiveSseStream replays terminal events after completion", async () => {
  const stream = new ActiveSseStream();
  stream.emit("delta", { text: "done" });
  stream.complete({ event: "done", data: { text: "done" } });
  await stream.done;

  const events: SseStreamEvent[] = [];
  stream.subscribe((event) => events.push(event));

  assert.equal(stream.isCompleted, true);
  assert.deepEqual(events, [
    { event: "delta", data: { text: "done" } },
    { event: "done", data: { text: "done" } },
  ]);
});
