const db = require('../db');

/**
 * Retrofit Simulations Script
 * 
 * This script iterates through all existing alerts and generates synthetic "simulation_data"
 * if it is missing. This simulation data drives the new "Micro-Simulator" interfaces
 * (SIEM, EDR, Firewall, etc.) without requiring a manual database wipe.
 */

const retrofitSimulations = async () => {
    console.log('🚀 Starting Simulation Data Retrofit...');

    try {
        // 1. Fetch all alerts that don't have simulation_data
        // We fetch basic fields needed to generate context-aware evidence
        const { rows: alerts } = await db.query(`
            SELECT id, title, source, severity, raw_log 
            FROM alerts 
            WHERE simulation_data IS NULL
        `);

        console.log(`🔍 Found ${alerts.length} alerts to retrofit.`);

        let updatedCount = 0;

        for (const alert of alerts) {
            const simData = generateSimulationData(alert);
            
            if (simData) {
                await db.query(
                    "UPDATE alerts SET simulation_data = ? WHERE id = ?",
                    [JSON.stringify(simData), alert.id]
                );
                updatedCount++;
                if (updatedCount % 50 === 0) process.stdout.write('.');
            }
        }

        console.log(`\n✅ Successfully retrofitted ${updatedCount} alerts with simulation data.`);

    } catch (error) {
        console.error('❌ Retrofit Failed:', error);
    } finally {
        // We do NOT close the pool explicitly because db.js might be sharing it, 
        // but for a standalone script, we should probably exit.
        // db.pool.end() is not exposed directly as a function in the exported object usually,
        // unless we exported 'pool'.
        // Checking src/db.js: 'pool' IS exported.
        if (db.pool) await db.pool.end();
        process.exit(0);
    }
};

/**
 * Generates appropriate simulation data based on the alert source
 */
function generateSimulationData(alert) {
    const source = (alert.source || '').toLowerCase();
    const title = (alert.title || '').toLowerCase();
    
    // Default structure
    const data = {
        tool: determineTool(source),
        evidence: []
    };

    // 1. SIEM (Splunk/ELK style)
    if (data.tool === 'SIEM') {
        data.evidence = generateSiemLogs(alert);
    }
    // 2. EDR (CrowdStrike/S1 style)
    else if (data.tool === 'EDR') {
        data.evidence = generateEdrData(alert);
    }
    // 3. Firewall (Palo Alto style)
    else if (data.tool === 'Firewall') {
        data.evidence = generateFirewallLogs(alert);
    }
    // 4. Mail Gateway
    else if (data.tool === 'Mail') {
        data.evidence = generateMailData(alert);
    }
    // 5. Identity
    else if (data.tool === 'Identity') {
        data.evidence = generateIdentityData(alert);
    }
    
    return data;
}

function determineTool(source) {
    if (source.includes('cloudtrail') || source.includes('splunk') || source.includes('windows') || source.includes('security log')) return 'SIEM';
    if (source.includes('crowdstrike') || source.includes('edr') || source.includes('endpoint') || source.includes('process')) return 'EDR';
    if (source.includes('firewall') || source.includes('network') || source.includes('waf')) return 'Firewall';
    if (source.includes('proofpoint') || source.includes('email') || source.includes('gateway')) return 'Mail';
    if (source.includes('active directory') || source.includes('auth') || source.includes('identity')) return 'Identity';
    
    // Default fallback
    return 'SIEM';
}

// --- Generators ---

function generateSiemLogs(alert) {
    // Context-aware log generation
    const logs = [];
    const baseTime = new Date().getTime();
    const title = (alert.title || '').toLowerCase();
    const source = (alert.source || '').toLowerCase();
    
    let logSource = '/var/log/syslog';
    let eventCode = 'INFO';
    let baseMessage = 'System event detected';

    // 1. Web Attacks (Nginx/Apache)
    if (title.includes('web') || title.includes('php') || title.includes('injection') || title.includes('xss')) {
        logSource = '/var/log/nginx/access.log';
        eventCode = '403';
        baseMessage = `GET /login.php?user=admin' OR '1'='1 HTTP/1.1 - 403 Forbidden - IP: 203.0.113.55`;
    } 
    // 2. Auth Failures (SSH/Windows)
    else if (title.includes('login') || title.includes('auth') || title.includes('password') || title.includes('brute')) {
        if (source.includes('windows')) {
            logSource = 'Security';
            eventCode = '4625';
            baseMessage = "An account failed to log on. Account: admin. Failure Reason: Unknown user name or bad password.";
        } else {
            logSource = '/var/log/auth.log';
            eventCode = 'Failed';
            baseMessage = "Failed password for invalid user admin from 192.168.1.50 port 49202 ssh2";
        }
    }
    // 3. Malware/System (Wazuh/Syslog)
    else if (source.includes('wazuh') || title.includes('malware') || title.includes('trojan')) {
        logSource = '/var/ossec/logs/alerts/alerts.json';
        eventCode = 'Rule: 1002';
        baseMessage = "File integrity changed for /etc/passwd. Checksum mismatch.";
    }

    // Generate a few variations
    for(let i=0; i<5; i++) {
        logs.push({
            timestamp: new Date(baseTime - (i * 60000)).toISOString(),
            source: logSource,
            event_code: eventCode,
            message: i === 0 ? baseMessage : `${baseMessage} [Repeated event count: ${i}]`,
            host: 'PRODUCTION-SVR-01',
            raw: alert.raw_log || 'Raw validation log unavailable'
        });
    }

    // Realistic Query Construction
    // If source is a file path, we use source="/path/to/log"
    // If source is 'Wazuh', the query should probably look at the agent or specific rule
    let query = `index=main source="${logSource}" | head 100`;
    
    return { events: logs, query: query };
}

function generateEdrData(alert) {
    return {
        hostname: 'WORKSTATION-01',
        os: 'Windows 10 Enterprise',
        agent_version: '7.12.0',
        process_tree: [
            { id: 100, name: 'explorer.exe', pid: 4520, user: 'jdoe', cmd: 'explorer.exe', 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: [] }
        ],
        network_connections: [
            { pid: 5100, remote_ip: '203.0.113.55', port: 443, state: 'ESTABLISHED', process: 'powershell.exe' }
        ]
    };
}

function generateFirewallLogs(alert) {
    return {
        policy_name: 'Block_Outbound_Direct_IP',
        action: 'ALLOW',
        interface_in: 'eth0',
        interface_out: 'eth1',
        packets: [
            { time: '10:00:01', src: '10.0.0.5', dst: '8.8.8.8', proto: 'UDP', port: 53, size: 120, action: 'ALLOW' },
            { time: '10:00:02', src: '10.0.0.5', dst: '203.0.113.15', proto: 'TCP', port: 443, size: 1500, action: 'ALLOW', alert: true },
        ]
    };
}

function generateMailData(alert) {
    return {
        headers: {
            from: 'urgent@support-microsoft-update.com', // Fake bad
            to: 'employee@company.com',
            subject: alert.title || 'Action Required',
            date: new Date().toISOString(),
            'x-mailer': 'PHPMailer 6.0'
        },
        attachments: [
            { name: 'invoice_feb.pdf.exe', size: '1.2MB', type: 'application/x-msdos-program', verdict: 'Malicious' }
        ],
        body_preview: 'Dear User, please check the attached invoice immediately...',
        security_check: 'FAIL - SPF/DKIM Mismatch'
    };
}

function generateIdentityData(alert) {
    return {
        user: {
            username: 'jdoe',
            display_name: 'John Doe',
            department: 'Finance',
            manager: 'Jane Smith'
        },
        risk_score: 85,
        recent_activity: [
            { action: 'Login Success', ip: '10.0.0.5', location: 'New York, US', time: '09:00 AM' },
            { action: 'Password Reset Request', ip: '192.168.1.5', location: 'New York, US', time: '09:05 AM' },
            { action: 'Login Failed', ip: '203.0.113.99', location: 'Moscow, RU', time: '02:00 AM', flag: true }
        ]
    };
}

// Run immediately
retrofitSimulations();
