import { createEvent } from "../hub/events";
import { InMemoryEventBus } from "../hub/eventBus";

async function main(): Promise<void> {
    const bus = new InMemoryEventBus();
    const seen: string[] = [];

    const unsubscribe = bus.on("chat_message", async (event) => {
        seen.push(`${event.name}:${event.payload.streamId}`);
    });

    await bus.emit(
        createEvent("chat_message", {
            streamId: "stream-1",
            platform: "test",
            author: "tester",
            message: "hello world"
        })
    );

    unsubscribe();

    await bus.emit(
        createEvent("chat_message", {
            streamId: "stream-2",
            platform: "test",
            author: "tester",
            message: "should not be seen"
        })
    );

    if (seen.length !== 1 || seen[0] !== "chat_message:stream-1") {
        throw new Error("Phase 4 smoke failed: event bus did not route handlers correctly.");
    }

    console.log(
        JSON.stringify(
            {
                ok: true,
                seen
            },
            null,
            2
        )
    );
}

main().catch((error: unknown) => {
    const message = error instanceof Error ? error.message : String(error);
    console.error(message);
    process.exit(1);
});
