/**
 * GET /v1/debug/memory/leak-detection
 * Ejecuta detección de fugas de memoria
 */

const memoryMonitor = require('../../../system/memory-monitor.slm');
const logger = require('../../../system/logger.slm');

module.exports = async (req, res, next, slmapi) => {
    try {
        const leakDetection = memoryMonitor.detectMemoryLeak();
        const stats = memoryMonitor.getMemoryStats();

        logger.info('Memory leak detection requested', {
            type: 'DEBUG_LEAK_DETECTION',
            ip: req.ip,
            detected: !!leakDetection,
            measurements: stats.measurements
        });

        if (!leakDetection) {
            return res.status(200).json({
                error: false,
                data: {
                    detected: false,
                    message: 'No memory leak detected',
                    measurements: stats.measurements,
                    minimumRequired: 10
                }
            });
        }

        return res.status(200).json({
            error: false,
            data: {
                detected: true,
                slope: leakDetection.slope,
                recommendation: leakDetection.recommendation,
                measurements: stats.measurements,
                averageHeapUsed: stats.average.heapUsedMB,
                peakHeapUsed: stats.peak.heapUsedMB
            }
        });

    } catch (error) {
        logger.error('Error detecting memory leak', {
            type: 'DEBUG_LEAK_DETECTION_ERROR',
            error: error.message
        });

        return res.status(500).json({
            error: true,
            message: 'Error al detectar fugas de memoria',
            details: error.message
        });
    }
};
