import { EventEmitter } from "events";
//#region src/infra/bus/queue.ts
/**
* Error thrown when MessageBus is shut down
*/
var MessageBusShutdownError = class extends Error {
	constructor() {
		super("MessageBus has been shut down");
		this.name = "MessageBusShutdownError";
	}
};
var MessageBus = class extends EventEmitter {
	inboundQueue = [];
	outboundQueue = [];
	inboundConsumers = [];
	outboundConsumers = [];
	isShutdown = false;
	async publishInbound(msg) {
		if (this.isShutdown) return;
		this.emit("inbound", msg);
		if (this.inboundConsumers.length > 0) this.inboundConsumers.shift()(msg);
		else this.inboundQueue.push(msg);
	}
	async publishOutbound(msg) {
		if (this.isShutdown) return;
		this.emit("outbound", msg);
		if (this.outboundConsumers.length > 0) this.outboundConsumers.shift()(msg);
		else this.outboundQueue.push(msg);
	}
	async consumeInbound() {
		if (this.isShutdown) throw new MessageBusShutdownError();
		return new Promise((resolve, reject) => {
			if (this.inboundQueue.length > 0) return resolve(this.inboundQueue.shift());
			const consumer = (msg) => {
				if (msg instanceof Error) reject(msg);
				else resolve(msg);
			};
			this.inboundConsumers.push(consumer);
		});
	}
	async consumeOutbound() {
		if (this.isShutdown) throw new MessageBusShutdownError();
		return new Promise((resolve, reject) => {
			if (this.outboundQueue.length > 0) return resolve(this.outboundQueue.shift());
			const consumer = (msg) => {
				if (msg instanceof Error) reject(msg);
				else resolve(msg);
			};
			this.outboundConsumers.push(consumer);
		});
	}
	/**
	* Shutdown the message bus and cancel all pending consumers
	*/
	shutdown() {
		if (this.isShutdown) return;
		this.isShutdown = true;
		const error = new MessageBusShutdownError();
		for (const consumer of this.inboundConsumers) consumer(error);
		for (const consumer of this.outboundConsumers) consumer(error);
		this.clear();
	}
	/**
	* Check if the bus has been shut down
	*/
	getShutdownState() {
		return this.isShutdown;
	}
	/**
	* Reset the bus state (for testing only)
	*/
	reset() {
		this.isShutdown = false;
		this.clear();
	}
	clear() {
		this.inboundQueue = [];
		this.outboundQueue = [];
		this.inboundConsumers = [];
		this.outboundConsumers = [];
	}
};
const bus = new MessageBus();
//#endregion
export { MessageBus, MessageBusShutdownError, bus };

//# sourceMappingURL=queue.js.map