require('dotenv').config({ path: '../../.env' }); // Adjust path to .env
const mysql = require('mysql2/promise');
const path = require('path');

// Fix .env path resolution if running from src/scripts
require('dotenv').config({ path: path.join(__dirname, '../../.env') });

async function migrate() {
    console.log('Connecting to database...');
    // Create connection
    const connection = await mysql.createConnection({
        host: process.env.DB_HOST || 'localhost',
        user: process.env.DB_USER || 'root',
        password: process.env.DB_PASSWORD || '',
        database: process.env.DB_NAME || 'infosecl_platform'
    });

    try {
        console.log('Fetching Alert 691...');
        const [rows] = await connection.execute('SELECT id, simulation_data, raw_log FROM alerts WHERE id = ?', [691]);
        
        if (rows.length === 0) {
            console.log('Alert 691 not found!');
            return;
        }

        const alert = rows[0];
        console.log('Current Raw Log length:', alert.raw_log ? alert.raw_log.length : 0);

        let simData;
        try {
            simData = typeof alert.simulation_data === 'string' ? JSON.parse(alert.simulation_data) : alert.simulation_data;
        } catch (e) {
            console.error('Failed to parse simulation_data');
            return;
        }

        if (!simData.evidence) {
            console.log('No evidence found in simulation_data. Skipping.');
            return;
        }

        // Use evidence as the new raw_log
        const newRawLog = JSON.stringify(simData.evidence, null, 2);
        console.log('New Raw Log length:', newRawLog.length);
        console.log('Preview:', newRawLog.substring(0, 100) + '...');

        await connection.execute('UPDATE alerts SET raw_log = ? WHERE id = ?', [newRawLog, 691]);
        console.log('Successfully updated Alert 691 raw_log with evidence data.');

    } catch (error) {
        console.error('Migration failed:', error);
    } finally {
        await connection.end();
    }
}

migrate();
