const mysql = require('mysql2/promise');

const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: '', // Empty password as per .env
    database: 'infosecl_platform',
};

async function patchData() {
    const connection = await mysql.createConnection(dbConfig);
    console.log('Connected to database.');

    try {
        // --- 1. Fix Alert 269 (EDR - BlackEnergy) ---
        // Problem: raw_log has 'word.exe', simulation has 'explorer' tree. Discrepancy.
        // Solution: Update raw_log to include the FULL process tree, making it the single source of truth.
        // We'll also update simulation_data to match, just in case.
        
        const processTree269 = [
            {
                "id": 100,
                "name": "winword.exe",
                "pid": 4321,
                "user": "jdoe",
                "cmd": "winword.exe /n \"C:\\Users\\jdoe\\Downloads\\invoice.doc\"",
                "integrity": "Medium",
                "children": [101]
            },
            {
                "id": 101,
                "name": "powershell.exe",
                "pid": 5100,
                "user": "jdoe",
                "cmd": "powershell.exe -nop -enc AAB...",
                "integrity": "High",
                "children": [102],
                "highlight": true
            },
            {
                "id": 102,
                "name": "conhost.exe",
                "pid": 5101,
                "user": "jdoe",
                "cmd": "conhost.exe",
                "integrity": "High",
                "children": []
            }
        ];

        const raw269 = {
            "timestamp": "2023-10-05T14:23:11Z",
            "hostname": "CORP-ENDPOINT-23",
            "os": "Windows 10 Enterprise",
            "username": "jdoe",
            "event_id": "987654321",
            "process_tree": processTree269, // INJECTING TREE INTO RAW LOG
            "alert_signature": "BlackEnergy Malware Execution"
        };
        
        const sim269 = {
            "tool": "EDR",
            "evidence": {
                "hostname": "CORP-ENDPOINT-23",
                "os": "Windows 10 Enterprise",
                "process_tree": processTree269
            }
        };

        await connection.execute(
            'UPDATE alerts SET raw_log = ?, simulation_data = ? WHERE id = 269',
            [JSON.stringify(raw269), JSON.stringify(sim269)]
        );
        console.log('✅ Patched Alert 269 (EDR)');


        // --- 2. Fix Alert 947 (Mail - BEC) ---
        // Problem: raw_log says BEC/Impressonation, Simulation says 'invoice.pdf.exe'.
        // Solution: Make Simulation match Raw Log (BEC scenario = No Attachment, just bad sender).
        
        const raw947 = {
            "timestamp": "2026-01-16T15:42:08Z",
            "event_type": "email_received",
            "email_sender": "ceo@companyl.com", // Typo-squatting domain
            "email_recipient": "finance@company.com",
            "subject": "Urgent Wire Transfer Request",
            "body_preview": "I need you to process this wire transfer immediately for the breakdown vendor. I am in a meeting, do not call.",
            "src_ip": "203.0.113.77",
            "user_agent": "Mozilla/5.0",
            "url": "http://malicious-transfer.com/funds"
        };

        const sim947 = {
            "tool": "Mail",
            "evidence": {
                "headers": {
                    "from": "ceo@companyl.com",
                    "to": "finance@company.com",
                    "subject": "Urgent Wire Transfer Request",
                    "date": "2026-01-16T15:42:08Z"
                },
                "body_preview": raw947.body_preview,
                "attachments": [], // No attachments for BEC
                "security_check": "FAIL - DMARC",
                "verdict": "Suspicious"
            }
        };

        await connection.execute(
            'UPDATE alerts SET raw_log = ?, simulation_data = ? WHERE id = 947',
            [JSON.stringify(raw947), JSON.stringify(sim947)]
        );
        console.log('✅ Patched Alert 947 (Mail BEC)');
        
        
        // --- 3. Fix Alert 318 (SIEM - Excessive Logins) ---
        // Make sure raw_log is consistent
        // It currently has 1 raw event but sim data has 5. 
        // We'll update raw_log to be an ARRAY of events so our new frontend logic (Array.isArray check) works perfectly.
        
        const events318 = [
             {"timestamp":"2026-02-01T20:32:18Z","event_code":"4625","src_ip":"192.168.1.50","username":"admin","message":"Failed login attempt"},
             {"timestamp":"2026-02-01T20:32:19Z","event_code":"4625","src_ip":"192.168.1.50","username":"admin","message":"Failed login attempt"},
             {"timestamp":"2026-02-01T20:32:20Z","event_code":"4625","src_ip":"192.168.1.50","username":"admin","message":"Failed login attempt"}
        ];
        
        const sim318 = {
            "tool": "SIEM",
            "evidence": {
                "events": events318
            }
        };

        await connection.execute(
            'UPDATE alerts SET raw_log = ?, simulation_data = ? WHERE id = 318',
            [JSON.stringify(events318), JSON.stringify(sim318)]
        );
        console.log('✅ Patched Alert 318 (SIEM)');

    } catch (e) {
        console.error('Error patching DB:', e);
    } finally {
        await connection.end();
    }
}

patchData();
