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

const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'infosecl_platform',
};

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

    try {
        // --- 1. Alert 1132: Daserf Backdoor (Operation Tick) ---
        // Raw log says: daserf.exe (PID 1345), Parent: ?
        const tree1132 = [
            { "id": 1, "name": "explorer.exe", "pid": 4520, "user": "jdoe", "cmd": "explorer.exe", "children": [2] },
            { "id": 2, "name": "daserf.exe", "pid": 1345, "user": "jdoe", "cmd": "daserf.exe", "integrity": "High", "children": [], "highlight": true }
        ];

        const raw1132 = {
            "timestamp": "2023-10-05T14:23:45Z",
            "event_id": "EDR-045672",
            "hostname": "WORKSTATION-01",
            "os": "Windows 10 Enterprise",
            "username": "jdoe",
            "source_ip": "204.152.201.7",
            "destination_ip": "192.168.1.25",
            "filename": "daserf.exe",
            "file_hash": "d41d8cd98f00b204e9800998ecf8427e",
            "process_tree": tree1132
        };
        await updateAlert(connection, 1132, raw1132, tree1132);


        // --- 2. Alert 609: Suspicious PowerShell (Training) ---
        // Scenario: PowerShell downloading content.
        const tree609 = [
            { "id": 1, "name": "explorer.exe", "pid": 1200, "user": "admin", "cmd": "explorer.exe", "children": [2] },
            { "id": 2, "name": "powershell.exe", "pid": 3400, "user": "admin", "cmd": "powershell.exe -ExecutionPolicy Bypass -File C:\\Temp\\script.ps1", "integrity": "Medium", "children": [3], "highlight": true },
            { "id": 3, "name": "conhost.exe", "pid": 3401, "user": "admin", "cmd": "conhost.exe", "children": [] }
        ];

        const raw609 = {
            "timestamp": "2026-02-01T10:00:00Z",
            "event_id": "EDR-609",
            "hostname": "WORKSTATION-01",
            "os": "Windows 10 Enterprise",
            "username": "admin", // Fixed to match tree
            "process_name": "powershell.exe",
            "command_line": "powershell.exe -ExecutionPolicy Bypass -File C:\\Temp\\script.ps1",
            "file_hash": "a1b2c3d4e5f67890",
            "process_tree": tree609
        };
        await updateAlert(connection, 609, raw609, tree609);


        // --- 3. Alert 1122: Macro Execution (Excel) ---
        // Raw log says: excel.exe (PID 3456) -> ?
        const tree1122 = [
            { "id": 1, "name": "excel.exe", "pid": 3456, "user": "jdoe", "cmd": "excel.exe \"invoice_2023.xlsm\"", "children": [2] },
            { "id": 2, "name": "powershell.exe", "pid": 4444, "user": "jdoe", "cmd": "powershell.exe -enc AAB...", "children": [], "highlight": true }
        ];
        
        const raw1122 = {
             "timestamp": "2023-10-12T14:22:18Z",
             "hostname": "WORKSTATION-01", 
             "os": "Windows 10 Enterprise",
             "event_type": "macro_execution",
             "username": "jdoe",
             "file_name": "invoice_2023.xlsm",
             "indicators": ["203.0.113.25"],
             "process_tree": tree1122
        };
        await updateAlert(connection, 1122, raw1122, tree1122);


        // --- 4. Alert 1118: Software Installation ---
        // Raw log: update.exe (PID 5678)
        const tree1118 = [
            { "id": 1, "name": "explorer.exe", "pid": 4000, "user": "jdoe", "children": [2] },
            { "id": 2, "name": "update.exe", "pid": 5678, "user": "jdoe", "cmd": "C:\\Program Files\\AccountingPro\\update.exe", "children": [], "highlight": true }
        ];
        
        const raw1118 = {
            "timestamp": "2023-10-12T14:32:00Z",
            "hostname": "WORKSTATION-01",
            "os": "Windows 10 Enterprise",
            "event_type": "software_installation",
            "username": "jdoe",
            "software_name": "AccountingPro Update",
            "file_hash": "5f4dcc3b5aa765d61d8327deb882cf99",
            "attacker_ip": "203.0.113.45",
            "process_tree": tree1118
        };
        await updateAlert(connection, 1118, raw1118, tree1118);


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

async function updateAlert(connection, id, rawLog, tree) {
    // We update BOTH raw_log AND simulation_data to be perfectly consistent.
    const simData = {
        "tool": "EDR",
        "evidence": {
            "hostname": rawLog.hostname,
            "os": rawLog.os,
            "agent_version": "7.12.0",
            "process_tree": tree,
            // Add fake network connections if needed, but tree is critical
             "network_connections": [] 
        }
    };

    console.log(`Patching Alert ${id}...`);
    await connection.execute(
        'UPDATE alerts SET raw_log = ?, simulation_data = ? WHERE id = ?',
        [JSON.stringify(rawLog), JSON.stringify(simData), id]
    );
    console.log(`✅ Patched Alert ${id}`);
}

fixEdrAlerts();
