/**
 * Middleware Stack
 * Refactored to Functional Object pattern
 */
export const MiddlewareStack = Object.freeze({
    /**
     * Create a new middleware stack instance
     */
    create() {
        const middlewares = [];
        return {
            /**
             * Register middleware
             */
            register(name, handler) {
                middlewares.push({ name, handler });
            },
            /**
             * Execute middleware stack
             */
            async execute(request, response, only) {
                const filteredMiddlewares = only
                    ? middlewares.filter((m) => only.includes(m.name))
                    : middlewares;
                let index = 0;
                const next = async () => {
                    if (index >= filteredMiddlewares.length)
                        return;
                    const middleware = filteredMiddlewares[index++];
                    await middleware.handler(request, response, next);
                };
                await next();
            },
            /**
             * Get all middleware
             */
            getMiddlewares() {
                return middlewares;
            },
        };
    },
});
export default MiddlewareStack;
