// SPDX-License-Identifier: Apache-2.0
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { EventEmitter as NodeEventEmitter } from 'node:events';
import { inject, injectable } from 'tsyringe-neo';
import { InjectTokens } from '../dependency-injection/inject-tokens.js';
import { patchInject } from '../dependency-injection/container-helper.js';
import { Duration } from '../time/duration.js';
import { SoloError } from '../errors/solo-error.js';
let DefaultSoloEventBus = class DefaultSoloEventBus {
    logger;
    emitter = new NodeEventEmitter();
    // Keep an in-memory log of all emitted events, grouped by event type.
    history = new Map();
    constructor(logger) {
        this.logger = logger;
        this.logger = patchInject(logger, InjectTokens.SoloLogger, this.constructor.name);
    }
    emit(event) {
        // Record event in history so callers can query or have waitFor resolve
        // even if the event was emitted before they started listening.
        let list = this.history.get(event.type);
        if (!list) {
            list = [];
            this.history.set(event.type, list);
        }
        list.push(event);
        // Log the event for debugging/inspection. Use debug level to avoid
        // cluttering normal output, but this can be changed if needed.
        this.logger.debug(`DefaultSoloEventBus.emit: type=${String(event.type)}`, event);
        this.emitter.emit(event.type, event);
    }
    on(type, handler) {
        this.emitter.on(type, handler);
    }
    off(type, handler) {
        this.emitter.off(type, handler);
    }
    clearHistory(type) {
        if (type === undefined) {
            this.history.clear();
        }
        else {
            this.history.delete(type);
        }
    }
    async waitFor(type, predicate, timeout = Duration.ofSeconds(60)) {
        return new Promise((resolve, reject) => {
            const timer = setTimeout(() => {
                this.emitter.off(type, handler);
                reject(new SoloError(`waitFor timed out after ${timeout.toMillis()}ms waiting for event type: ${String(type)}`));
            }, timeout.toMillis());
            // Ensure we only resolve once if handler and history check race.
            let settled = false;
            // Register handler first to avoid missing events that arrive while
            // we're checking the history.
            const handler = (event) => {
                try {
                    if (!predicate || predicate(event)) {
                        if (settled) {
                            return;
                        }
                        settled = true;
                        clearTimeout(timer);
                        this.emitter.off(type, handler);
                        resolve(event);
                    }
                }
                catch (error) {
                    clearTimeout(timer);
                    this.emitter.off(type, handler);
                    reject(new SoloError(`Error in waitFor handler predicate for event type: ${String(type)}`, error));
                }
            };
            this.emitter.on(type, handler);
            // Then check the history for already-emitted events (newest first).
            const events = this.history.get(type);
            if (events) {
                for (let index = events.length - 1; index >= 0; index--) {
                    const candidate = events[index];
                    try {
                        if (!predicate || predicate(candidate)) {
                            if (settled) {
                                return;
                            }
                            settled = true;
                            clearTimeout(timer);
                            this.emitter.off(type, handler);
                            resolve(candidate);
                            return;
                        }
                    }
                    catch (error) {
                        clearTimeout(timer);
                        this.emitter.off(type, handler);
                        reject(new SoloError(`Error in waitFor history check predicate for event type: ${String(type)}`, error));
                    }
                }
            }
        });
    }
};
DefaultSoloEventBus = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.SoloLogger)),
    __metadata("design:paramtypes", [Object])
], DefaultSoloEventBus);
export { DefaultSoloEventBus };
//# sourceMappingURL=default-solo-event-bus.js.map