/**
 * GET /v1/debug/heap-snapshot
 * Genera un heap snapshot para análisis
 */

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

module.exports = async (req, res, next, slmapi) => {
    try {
        const timestamp = Date.now();
        const filename = `heap-${timestamp}.heapsnapshot`;
        const filepath = path.join(__dirname, '../../../../', filename);

        logger.info('Heap snapshot generation requested', {
            type: 'DEBUG_HEAP_SNAPSHOT',
            ip: req.ip,
            filename
        });

        // Generar snapshot
        const snapshotStream = v8.writeHeapSnapshot(filepath);

        if (!snapshotStream || !fs.existsSync(filepath)) {
            throw new Error('Failed to generate heap snapshot');
        }

        // Obtener tamaño del archivo
        const stats = fs.statSync(filepath);
        const sizeMB = (stats.size / 1024 / 1024).toFixed(1);

        logger.info('Heap snapshot generated successfully', {
            type: 'DEBUG_HEAP_SNAPSHOT_SUCCESS',
            file: filepath,
            sizeMB
        });

        return res.status(200).json({
            error: false,
            data: {
                success: true,
                file: filepath,
                filename,
                size: `${sizeMB} MB`,
                timestamp,
                message: 'Download and analyze in Chrome DevTools',
                instructions: [
                    '1. Download the file from the container',
                    '2. Open Chrome DevTools (F12)',
                    '3. Go to Memory tab',
                    '4. Click "Load" and select the .heapsnapshot file',
                    '5. Analyze objects and references'
                ]
            }
        });

    } catch (error) {
        logger.error('Error generating heap snapshot', {
            type: 'DEBUG_HEAP_SNAPSHOT_ERROR',
            error: error.message
        });

        return res.status(500).json({
            error: true,
            message: 'Error al generar heap snapshot',
            details: error.message
        });
    }
};
