const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../../.env') });
const db = require('../db');

// Helper to run query with explicit promise wrapper if needed, though db.query is likely async
const runQuery = async (sql, params = []) => {
    return await db.query(sql, params);
};

const learningPath = {
    title: "Alert Investigation Specialist",
    description: "Master the art of investigating specific security alerts. Deep dive into EDR, SIEM, Network, and Email analysis tools.",
    difficulty: "Intermediate",
    display_order: 3 // Placing it after Fundamentals
};

const modules = [
    {
        title: "EDR Investigations",
        tasks: [
            { title: "Understanding EDR Telemetry", content: "# EDR Telemetry\n\nEndpoint Detection and Response (EDR) tools record visible activities on endpoints.\n\n## Key Data Points\n* **Process Execution**: What ran? (cmd.exe, powershell.exe)\n* **File Modifications**: What was created/deleted?\n* **Network Connections**: Who did it talk to?" },
            { title: "Analyzing Process Trees", content: "# Process Trees 🌳\n\nMalware rarely runs alone. It spawns child processes.\n\n## Parent-Child Relationships\n* **Normal**: `explorer.exe` -> `chrome.exe`\n* **Suspicious**: `winword.exe` -> `powershell.exe` (Macro malware)\n* **Suspicious**: `svchost.exe` -> `cmd.exe`" },
            { title: "Detecting Lateral Movement", content: "# Lateral Movement\n\nAttackers move from machine to machine.\n\n## Indicators\n* **PsExec**: Look for `PSEXESVC.exe`.\n* **RDP**: Look for `mstsc.exe` with unusual arguments.\n* **WMI**: `wmic process call create`." },
            { title: "Memory Injection Techniques", content: "# Memory Injection 💉\n\nHiding code inside another running process.\n\n## Techniques\n* **DLL Injection**: Forcing a process to load a malicious DLL.\n* **Reflective DLL Loading**: Loading DLL from memory, not disk (Fileless).\n* **Hollow Process Injection**: Creating a suspended process, replacing its code, and resuming." },
            { title: "Isolating infected Hosts", content: "# Containment 🛑\n\nThe first step in response is stopping the bleeding.\n\n## Network Isolation\nMost EDRs have a \"Network Containment\" button. This blocks all traffic EXPECT to the EDR managment server." }
        ]
    },
    {
        title: "Network Forensics (NTA)",
        tasks: [
            { title: "Identifying Beaconing", content: "# Beaconing 📡\n\nMalware calls home to the C2 server at regular intervals.\n\n## Patterns\n* **Jitter**: Randomized intervals (e.g., every 60s +/- 10%).\n* **Long Connections**: Connections that stay open for hours." },
            { title: "Data Exfiltration Detection", content: "# Data Exfiltration 📤\n\nStealing data.\n\n## Signs\n* **Large Uploads**: 5GB sent to an unknown IP.\n* **Encrypted Traffic**: High entropy data.\n* **DNS Tunneling**: Huge volume of DNS queries to a single domain." },
            { title: "Analyzing PCAP Files", content: "# PCAP Analysis\n\nUsing Wireshark to carve files.\n\n## Carving\n1. Find `HTTP` stream.\n2. Look for `GET /malware.exe`.\n3. File -> Export Objects -> HTTP. Save the file for analysis." },
            { title: "Detecting C2 Traffic", content: "# C2 Channels\n\nCommand and Control.\n\n## Common Protocols\n* **HTTP/S**: Blends in with browsing.\n* **DNS**: Hard to block.\n* **IRC**: Old school but still used." },
            { title: "Firewall Log Analysis", content: "# Firewall Logs 🔥\n\n* **DENY**: Someone tried to get in but failed.\n* **ALLOW**: They got in. Was it authorized?\n* **Scan Detection**: One IP hitting 1000 ports in 1 second." }
        ]
    },
    {
        title: "SIEM Log Analysis",
        tasks: [
            { title: "Writing SPL (Search Processing Language)", content: "# Splunk SPL Basics\n\n* `index=main src_ip=10.0.0.5`\n* `stats count by dest_port`\n* `table _time, src_ip, dest_ip, action`" },
            { title: "Correlating Events", content: "# Correlation\n\nConnecting the dots.\n\n* **Event A**: Brute force failure (4625) x 100.\n* **Event B**: Success login (4624).\n* **Conclusion**: Successful brute force attack." },
            { title: "Windows Event Codes", content: "# Critical Event IDs 🆔\n\n* **4624**: Successful Login.\n* **4625**: Failed Login.\n* **4720**: User Created.\n* **4672**: Admin Login (Special Privileges)." },
            { title: "Linux Syslog Analysis", content: "# Syslog\n\n* `/var/log/auth.log`: Auth attempts.\n* `/var/log/syslog`: General messages.\n* **Sudo abuse**: Look for `COMMAND` execution in auth logs." },
            { title: "Baseline vs Anomaly", content: "# Baselines\n\nKnow what is normal.\n* **Normal**: User logs in at 9 AM, out at 5 PM.\n* **Anomaly**: User logs in at 3 AM from North Korea." }
        ]
    },
    {
        title: "Email Security & Phishing",
        tasks: [
            { title: "Analyzing Email Headers", content: "# Email Headers 📧\n\n* **Received**: Shows the hops the email took (Bottom to top).\n* **Return-Path**: Where bounces go (often the true sender).\n* **X-Originating-IP**: The sender's IP." },
            { title: "SPF, DKIM, DMARC", content: "# Email Auth Protocols\n\n* **SPF**: List of approved IPs allowed to send mail for a domain.\n* **DKIM**: Cryptographic signature on the email.\n* **DMARC**: Policy (Reject, Quarantine, None) if SPF/DKIM fail." },
            { title: "Malicious Attachment Analysis", content: "# Attachments 📎\n\n* **Office Macros**: `.docm`, `.xlsm`.\n* **Double Extension**: `invoice.pdf.exe`.\n* **OLE Objects**: Embedded scripts." },
            { title: "Phishing vs Spear Phishing", content: "# Types of Phishing 🎣\n\n* **Phishing**: Spray and pray.\n* **Spear Phishing**: Targeted at a specific person.\n* **Whaling**: Targeted at Executives (CEO/CFO)." },
            { title: "URL Analysis", content: "# URL Sandboxing\n\n* Don't click it!\n* Use `UrlScan.io` or `VirusTotal`.\n* Look for **Typosquatting**: `gooogle.com`." }
        ]
    },
    {
        title: "Vulnerability Management",
        tasks: [
            { title: "CVSS Scoring System", content: "# CVSS (Common Vulnerability Scoring System)\n\n* **Low**: 0.1 - 3.9\n* **Medium**: 4.0 - 6.9\n* **High**: 7.0 - 8.9\n* **Critical**: 9.0 - 10.0\n\n## Vector\n* **AV (Attack Vector)**: Network (bad) vs Physical (less bad)." },
            { title: "Prioritizing Patches", content: "# Patch Management\n\nYou can't patch everything.\n\n## Factors\n1. **Exploitability**: Is there exploit code available?\n2. **Criticality**: Is it an internet-facing server?\n3. **Severity**: Is it RCE (Remote Code Execution)?" },
            { title: "False Positives", content: "# False Positives ✅\n\nScanner says it's vulnerable, but it's not.\n* **Backporting**: Installing security fix without changing version number (Common in Linux).\n* **Configuration**: Feature is installed but disabled." },
            { title: "Authenticated vs Unauthenticated Scanning", content: "# Scan Types\n\n* **Unauthenticated**: Outside looking in (Simulates external hacker).\n* **Authenticated**: Logging in to check registry keys/file versions (More accurate)." },
            { title: "Remediation Reports", content: "# Reporting\n\n* Don't just dump a PDF.\n* Validated the finding.\n* Provide a clear fix (Update to v1.2.3).\n* Set a deadline." }
        ]
    }
];

async function seed() {
    try {
        console.log("🚀 Starting Alert Investigation Path Seed...");

        // 1. Create Learning Path
        let pathId;
        console.log("Creating Learning Path...");
        const pathResult = await runQuery(
            `INSERT INTO learning_paths (title, description, display_order) VALUES (?, ?, ?)`, 
            [learningPath.title, learningPath.description, learningPath.display_order]
        );
        // Handle different return types (mysql2 vs pg style in wrapper)
        pathId = pathResult.insertId || pathResult.rows[0].id;
        console.log(`✅ Path Created: ${learningPath.title} (ID: ${pathId})`);

        // 2. Loop Modules
        for (const [modIndex, moduleData] of modules.entries()) {
            console.log(`  Creating Module: ${moduleData.title}...`);
            const modResult = await runQuery(
                `INSERT INTO modules (learning_path_id, title, description, display_order) VALUES (?, ?, ?, ?)`,
                [pathId, moduleData.title, `Learn about ${moduleData.title}`, modIndex + 1]
            );
            const moduleId = modResult.insertId || modResult.rows[0].id;

            // 3. Loop Tasks
            for (const [taskIndex, taskData] of moduleData.tasks.entries()) {
                console.log(`    Creating Task: ${taskData.title}...`);
                const taskResult = await runQuery(
                    `INSERT INTO tasks (module_id, title, xp_reward, display_order) VALUES (?, ?, ?, ?)`,
                    [moduleId, taskData.title, 50, taskIndex + 1]
                );
                const taskId = taskResult.insertId || taskResult.rows[0].id;

                // 4. Insert Content
                await runQuery(
                    `INSERT INTO lesson_content (task_id, content) VALUES (?, ?)`,
                    [taskId, taskData.content]
                );
            }
        }

        console.log("✨ Seed Complete!");
        process.exit(0);

    } catch (error) {
        console.error("❌ Seed Failed:", error);
        process.exit(1);
    }
}

seed();
