"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.eventRegistry = void 0;
const logger_1 = require("../logger");
class LTEventRegistry {
    constructor() {
        this.adapters = [];
        this.connected = false;
    }
    /**
     * Register an event adapter. Call before connect().
     */
    register(adapter) {
        this.adapters.push(adapter);
    }
    /**
     * Connect all registered adapters. Call during startup.
     */
    async connect() {
        if (this.connected)
            return;
        await Promise.allSettled(this.adapters.map((a) => a.connect()));
        this.connected = true;
    }
    /**
     * Publish an event to all registered adapters.
     * Best-effort: individual adapter failures are logged, not thrown.
     */
    async publish(event) {
        if (!this.adapters.length)
            return;
        await Promise.allSettled(this.adapters.map((a) => a.publish(event).catch((err) => {
            logger_1.loggerRegistry.error(`[lt-events] adapter publish failed: ${err?.message}`);
        })));
    }
    /**
     * Disconnect all registered adapters. Call during shutdown.
     */
    async disconnect() {
        await Promise.allSettled(this.adapters.map((a) => a.disconnect()));
        this.connected = false;
    }
    /**
     * Remove all adapters and reset state. Used in tests.
     */
    clear() {
        this.adapters = [];
        this.connected = false;
    }
    /**
     * Check if any adapters are registered.
     */
    get hasAdapters() {
        return this.adapters.length > 0;
    }
    /**
     * Return the first registered adapter that matches the given type.
     */
    getAdapter(ctor) {
        return this.adapters.find((a) => a instanceof ctor);
    }
    /**
     * Bridge cross-container events to the in-process callback adapter.
     *
     * Iterates all registered adapters and calls `setCallbackBridge()` on
     * any that implement it. This is the generic contract — any transport
     * adapter (NATS, SNS, GCP Pub/Sub, Kafka) that supports cross-process
     * delivery implements `setCallbackBridge` on the LTEventAdapter interface.
     */
    bridgeCallbackAdapter(callbackAdapter) {
        let bridged = 0;
        for (const adapter of this.adapters) {
            if (adapter !== callbackAdapter && typeof adapter.setCallbackBridge === 'function') {
                adapter.setCallbackBridge(callbackAdapter);
                bridged++;
            }
        }
        logger_1.loggerRegistry.info(`[lt-events] callback bridge wired to ${bridged} transport adapter(s)`);
    }
}
/** Singleton event registry */
exports.eventRegistry = new LTEventRegistry();
