"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CallbackEventAdapter = void 0;
const logger_1 = require("../logger");
const matching_1 = require("./matching");
/**
 * In-process event adapter that delivers events via registered callbacks.
 *
 * Plugs into the existing `eventRegistry` alongside Socket.IO / NATS.
 * SDK callers subscribe with `.on()` and receive events as direct
 * function calls — no network transport, no serialization overhead.
 *
 * Supports NATS-style pattern matching:
 * - Exact: `on('task.created', cb)`
 * - Single-token wildcard: `on('task.*', cb)` — matches task.created, task.failed, etc.
 * - Multi-token wildcard: `on('app.epic.>', cb)` — matches app.epic.apis.createorder.error
 * - Global wildcard: `on('*', cb)` — matches every event
 */
class CallbackEventAdapter {
    constructor() {
        this.listeners = new Map();
    }
    /**
     * Subscribe to events by type, pattern, or wildcard.
     * Returns an unsubscribe function.
     */
    on(pattern, callback) {
        let set = this.listeners.get(pattern);
        if (!set) {
            set = new Set();
            this.listeners.set(pattern, set);
        }
        set.add(callback);
        return () => {
            set.delete(callback);
            if (set.size === 0) {
                this.listeners.delete(pattern);
            }
        };
    }
    async connect() {
        logger_1.loggerRegistry.info('[lt-events:callback] adapter connected');
    }
    async publish(event) {
        for (const [pattern, callbacks] of this.listeners) {
            if ((0, matching_1.subjectMatchesPattern)(event.type, pattern)) {
                for (const cb of callbacks) {
                    try {
                        cb(event);
                    }
                    catch { /* fire-and-forget */ }
                }
            }
        }
    }
    async disconnect() {
        this.listeners.clear();
        logger_1.loggerRegistry.info('[lt-events:callback] adapter disconnected');
    }
}
exports.CallbackEventAdapter = CallbackEventAdapter;
