const mysql = require('mysql2/promise');
require('dotenv').config();

const randomDate = (start, end) => {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
};

const ips = ['192.168.1.100', '192.168.1.101', '192.168.1.102', '10.0.0.50', '10.0.0.51', '10.0.0.52', '172.16.0.2', '172.16.0.3'];
const actions = ['allowed', 'blocked', 'denied', 'success', 'failed'];
const users = ['jdoe', 'asmith', 'bwayne', 'ckent', 'system', 'root', 'admin'];

const maliciousHashes = [
    'A5F3C6A2188E62215A5A90E0AC823907', // Simulated Mimikatz
    'B2A10C94F6E500A138A75F865F36CC11', // Simulated Emotet
    'D80C68AA9047BA6C8AFEBEBB65620922', // Simulated Ransomware
    'E2945D165CB6019A82D19D827131F50A'  // Simulated C2 Beacon
];

const maliciousProcesses = ['mimikatz.exe', 'powershell.exe', 'cmd.exe', 'certutil.exe', 'psexec.exe', 'wmic.exe', 'svchost.exe'];
const legitimateProcesses = ['chrome.exe', 'explorer.exe', 'winword.exe', 'outlook.exe', 'teams.exe', 'excel.exe', 'spotify.exe'];

async function seed() {
    try {
        const pool = mysql.createPool({
            host: process.env.DB_HOST || 'localhost',
            user: process.env.DB_USER || 'root',
            password: process.env.DB_PASSWORD || '',
            database: process.env.DB_NAME || 'infosec_db',
            waitForConnections: true,
            connectionLimit: 10,
            queueLimit: 0
        });

        console.log("Seeding simulated logs...");
        
        // Let's seed 500 records
        const records = 500;
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - 30); // over the last 30 days
        
        let logs = [];

        for(let i=0; i<records; i++) {
            // Determine log type with weighted probabilities
            const rand = Math.random();
            let indexName = 'firewall_traffic';
            if (rand < 0.2) indexName = 'aws_cloudtrail';
            else if (rand < 0.4) indexName = 'windows_events';
            else if (rand < 0.6) indexName = 'sysmon_events';
            else if (rand < 0.7) indexName = 'crowdstrike_edr';
            
            const sourceIp = ips[Math.floor(Math.random() * ips.length)];
            const destIp = `1.2.3.${Math.floor(Math.random() * 255)}`;
            const action = actions[Math.floor(Math.random() * actions.length)];
            const user = users[Math.floor(Math.random() * users.length)];
            
            let rawData = {};
            
            if(indexName === 'firewall_traffic') {
                rawData = {
                    src_ip: sourceIp,
                    dst_ip: destIp,
                    action: action,
                    port: Math.random() > 0.5 ? 443 : 80,
                    protocol: 'TCP',
                    bytes_in: Math.floor(Math.random() * 5000),
                    bytes_out: Math.floor(Math.random() * 10000)
                };
            } else if (indexName === 'windows_events') {
                const eventIds = [4624, 4625, 4634, 4688, 5140];
                const eid = eventIds[Math.floor(Math.random() * eventIds.length)];
                rawData = {
                    EventID: eid,
                    User: user,
                    LogonType: Math.random() > 0.5 ? 3 : 10,
                    Status: action === 'success' || action === 'allowed' ? 'Success Audit' : 'Failure Audit'
                };
            } else if (indexName === 'sysmon_events') {
                const isMalicious = Math.random() < 0.3; // 30% chance of being malicious
                const procList = isMalicious ? maliciousProcesses : legitimateProcesses;
                const procName = procList[Math.floor(Math.random() * procList.length)];
                
                rawData = {
                    EventID: 1, // Process Creation
                    User: `WORKGROUP\\${user}`,
                    ProcessName: `C:\\Windows\\System32\\${procName}`,
                    CommandLine: isMalicious ? `"${procName}" -enc JABzAD0ATgBlAHcALQBPAGIAagBlAGMAdAAgAEkATwAuAE0AZQBtAG8AcgB5AFMAdAByAGUAYQBtACgAWwBDAG8AbgB2AGUAcgB0AF0AOgA6AEYAcgBvAG0AQgBhAHMAZQA2ADQAUwB0AHIAaQBuAGcAKAAiAEgA...` : `"${procName}" --started`,
                    ParentProcessName: "C:\\Windows\\explorer.exe",
                    Hashes: `SHA1=${Math.random().toString(36).substring(2, 15).toUpperCase()},MD5=${isMalicious ? maliciousHashes[Math.floor(Math.random() * maliciousHashes.length)] : 'E2945D165CB6019A82D19D827131F50A'},IMPHASH=00000000000000000000000000000000`
                };
            } else if (indexName === 'crowdstrike_edr') {
                const procName = maliciousProcesses[Math.floor(Math.random() * maliciousProcesses.length)];
                const hash = maliciousHashes[Math.floor(Math.random() * maliciousHashes.length)];
                rawData = {
                    alert_name: "Credential Dumping Activity Detected",
                    severity: "High",
                    sensor_id: `win-srv-${Math.floor(Math.random() * 100)}`,
                    tactic: "Credential Access",
                    technique: "T1003",
                    process_name: procName,
                    file_path: `C:\\Users\\${user}\\Downloads\\${procName}`,
                    sha256: hash,
                    action_taken: Math.random() > 0.5 ? "Killed" : "Blocked"
                };
            } else {
                rawData = {
                    eventSource: 's3.amazonaws.com',
                    eventName: 'GetObject',
                    userIdentity: { userName: user },
                    sourceIPAddress: sourceIp,
                    userAgent: 'aws-cli/2.0.0'
                };
            }

            // Using local time
            logs.push([
                indexName,
                randomDate(startDate, endDate),
                sourceIp,
                destIp,
                JSON.stringify(rawData)
            ]);
        }
        
        await pool.query('INSERT INTO simulated_logs (index_name, timestamp, source_ip, dest_ip, raw_data) VALUES ?', [logs]);
        console.log(`Successfully seeded ${records} dummy logs into 'simulated_logs' table.`);
        
        process.exit(0);
    } catch (e) {
        console.error("Error seeding logs:", e);
        process.exit(1);
    }
}

seed();
