import type { DataStore } from "../db/store";
import type { InMemoryEventBus } from "./eventBus";
import { createEvent } from "./events";

type FanoutLog = (message: string, fields?: Record<string, unknown>) => void;

export function attachChatIngestFanout(
    eventBus: InMemoryEventBus,
    dataStore: DataStore,
    _log: FanoutLog
): () => void {
    return eventBus.on(
        "chat_ingest",
        async (event) => {
            const streams = await dataStore.listStreams();
            if (streams.length === 0) {
                return;
            }

            for (const stream of streams) {
                await eventBus.emit(
                    createEvent("chat_message", {
                        streamId: stream.id,
                        platform: event.payload.platform,
                        author: event.payload.author,
                        message: event.payload.message
                    })
                );
            }
        },
        {
            componentId: "chat-ingest-fanout",
            componentKind: "core"
        }
    );
}
