import { describe, it, expect } from "vitest";
import { eventBus, type PMEvent } from "@/lib/events/bus";

describe("eventBus", () => {
  it("delivers an emitted event to subscribers", async () => {
    const received: PMEvent[] = [];
    const unsub = eventBus.subscribe((e) => received.push(e));
    eventBus.emit({ type: "project.updated", projectId: "p1" });
    eventBus.emit({ type: "commit.new", projectId: "p1", hash: "abc" });
    unsub();
    expect(received).toEqual([
      { type: "project.updated", projectId: "p1" },
      { type: "commit.new", projectId: "p1", hash: "abc" },
    ]);
  });

  it("unsubscribed listener stops receiving events", () => {
    const received: PMEvent[] = [];
    const unsub = eventBus.subscribe((e) => received.push(e));
    unsub();
    eventBus.emit({ type: "project.updated", projectId: "p2" });
    expect(received).toHaveLength(0);
  });

  it("supports multiple concurrent subscribers", () => {
    const a: PMEvent[] = [];
    const b: PMEvent[] = [];
    const ua = eventBus.subscribe((e) => a.push(e));
    const ub = eventBus.subscribe((e) => b.push(e));
    eventBus.emit({ type: "project.updated", projectId: "p3" });
    ua(); ub();
    expect(a).toHaveLength(1);
    expect(b).toHaveLength(1);
  });
});
