/**
 * POST /v1/debug/gc
 * Fuerza garbage collection (requiere --expose-gc)
 */

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

module.exports = async (req, res, next, slmapi) => {
    try {
        // Verificar si GC está disponible
        if (typeof global.gc !== 'function') {
            logger.warning('GC not available (requires --expose-gc flag)', {
                type: 'DEBUG_GC_NOT_AVAILABLE',
                ip: req.ip
            });

            return res.status(400).json({
                error: true,
                message: 'Garbage collection no está disponible',
                details: 'El servidor debe iniciarse con la bandera --expose-gc',
                example: 'node --expose-gc server.js'
            });
        }

        // Obtener métricas antes de GC
        const before = memoryMonitor.getMemoryMetrics();

        logger.info('Manual GC requested', {
            type: 'DEBUG_GC',
            ip: req.ip,
            beforeHeapUsedMB: before.heapUsedMB,
            beforeHeapPercentage: before.heapPercentage
        });

        // Ejecutar garbage collection
        global.gc();

        // Esperar un momento para que se complete
        await new Promise(resolve => setTimeout(resolve, 100));

        // Obtener métricas después de GC
        const after = memoryMonitor.getMemoryMetrics();
        const freedMB = before.heapUsedMB - after.heapUsedMB;

        logger.info('Manual GC completed', {
            type: 'DEBUG_GC_SUCCESS',
            freedMB,
            beforeHeapUsedMB: before.heapUsedMB,
            afterHeapUsedMB: after.heapUsedMB
        });

        return res.status(200).json({
            error: false,
            data: {
                success: true,
                before: {
                    heapUsedMB: before.heapUsedMB,
                    heapTotalMB: before.heapTotalMB,
                    heapPercentage: before.heapPercentage
                },
                after: {
                    heapUsedMB: after.heapUsedMB,
                    heapTotalMB: after.heapTotalMB,
                    heapPercentage: after.heapPercentage
                },
                freed: {
                    mb: freedMB,
                    percentage: Math.round(((freedMB / before.heapUsedMB) * 100) * 100) / 100
                },
                message: freedMB > 0
                    ? `Freed ${freedMB} MB of memory`
                    : 'No significant memory freed (possibly already clean)'
            }
        });

    } catch (error) {
        logger.error('Error executing garbage collection', {
            type: 'DEBUG_GC_ERROR',
            error: error.message
        });

        return res.status(500).json({
            error: true,
            message: 'Error al ejecutar garbage collection',
            details: error.message
        });
    }
};
