module.exports = {
    friendlyName: 'Merge deep objects',

    description: 'Deep merge two objects with security considerations',

    inputs: {
        target: {
            type: 'ref',
            required: true,
            description: 'Target object to merge into'
        },
        source: {
            type: 'ref',
            required: true,
            description: 'Source object to merge from'
        }
    },

    fn: async function (inputs, exits) {
        const { target, source } = inputs;

        // Fonction de fusion profonde sécurisée
        const mergeDeep = (targetObj, sourceObj) => {
            if (!sourceObj || typeof sourceObj !== 'object') {
                return targetObj;
            }

            if (!targetObj || typeof targetObj !== 'object') {
                return sourceObj;
            }

            const result = { ...targetObj };

            for (const key in sourceObj) {
                if (sourceObj.hasOwnProperty(key)) {
                    // Vérifier que la clé est autorisée (éviter l'injection de propriétés malveillantes)
                    if (typeof key === 'string' && /^[a-zA-Z0-9_]+$/.test(key)) {
                        if (sourceObj[key] && typeof sourceObj[key] === 'object' && !Array.isArray(sourceObj[key])) {
                            result[key] = mergeDeep(result[key], sourceObj[key]);
                        } else {
                            result[key] = sourceObj[key];
                        }
                    } else {
                        sails.log.warn(`Skipping potentially unsafe key: ${key}`);
                    }
                }
            }

            return result;
        };

        try {
            const merged = mergeDeep(target, source);
            return exits.success(merged);
        } catch (error) {
            sails.log.error('Error in mergeDeep:', error);
            return exits.error(error);
        }
    }
};
