"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createStepHandlers = void 0;
const logger_1 = require("./logger");
const call_step_file_1 = require("./call-step-file");
const createStepHandlers = (lockedData, eventManager, state) => {
    const eventSteps = lockedData.eventSteps();
    const printer = lockedData.printer;
    logger_1.globalLogger.debug(`[step handler] creating step handlers for ${eventSteps.length} steps`);
    const removeLogger = (event) => {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { logger, ...rest } = event;
        return rest;
    };
    const createHandler = (step) => {
        const { config, filePath } = step;
        const { subscribes, name } = config;
        logger_1.globalLogger.debug('[step handler] establishing step subscriptions', { filePath, step: step.config.name });
        subscribes.forEach((subscribe) => {
            eventManager.subscribe({
                filePath,
                event: subscribe,
                handlerName: step.config.name,
                handler: async (event) => {
                    const { logger, data, traceId } = event;
                    logger_1.globalLogger.debug('[step handler] received event', { event: removeLogger(event), step: name });
                    try {
                        await (0, call_step_file_1.callStepFile)({
                            contextInFirstArg: false,
                            step,
                            printer,
                            eventManager,
                            state,
                            data,
                            traceId,
                            logger,
                        });
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    }
                    catch (error) {
                        const message = typeof error === 'string' ? error : error.message;
                        logger.error(message);
                    }
                },
            });
        });
    };
    const removeHandler = (step) => {
        const { config, filePath } = step;
        const { subscribes } = config;
        subscribes.forEach((subscribe) => {
            eventManager.unsubscribe({ filePath, event: subscribe });
        });
    };
    eventSteps.forEach(createHandler);
    return { removeHandler, createHandler };
};
exports.createStepHandlers = createStepHandlers;
