/*
 * @Author: sunhaolin@hotoa.com
 * @Date: 2022-12-21 15:06:15
 * @LastEditors: sunhaolin@hotoa.com
 * @LastEditTime: [当前日期]
 * @Description: Step management utilities
 */

const _ = require('lodash');

// 使用Map替代全局对象，更安全且性能更好
const stepManager = new Map();

/**
 * Check if a step allows batch processing
 * @param {Object} step - The step object to check
 * @returns {boolean} - Returns true if batch processing is allowed
 */
stepManager.allowBatch = function(step) {
    return !!step?.allowBatch;
};

/**
 * Get a step from flow instance
 * @param {Object} instance - The flow instance object
 * @param {Object} flow - The flow object containing current and history versions
 * @param {string} step_id - The ID of the step to find
 * @returns {Promise<Object>} - The found step object
 * @throws {Error} - If step cannot be found
 */
stepManager.getStep = async function(instance, flow, step_id) {
    const flow_rev = instance.flow_version;
    let isExistStep = null;

    if (flow.current._id === flow_rev) {
        isExistStep = _.find(flow.current.steps, step => step._id === step_id);
    } else {
        for (const history of flow.historys) {
            if (history._id === flow_rev) {
                isExistStep = _.find(history.steps, step => step._id === step_id);
                if (isExistStep) break;
            }
        }
    }

    if (!isExistStep) {
        throw new Error('Cannot find step');
    }

    return isExistStep;
};

// 导出模块
module.exports = stepManager;