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

const overview = {
    id: 25,
    title: 'Intrusion Detection',
    description: 'Learn to identify and investigate network and host-based intrusions.',
    learning_path_id: 3
};

const tasks = [
    { id: 251, title: 'IDS Types: NIDS vs HIDS' },
    { id: 252, title: 'Signature vs Anomaly Detection' },
    { id: 253, title: 'Snort: The Open-Source IDS' },
    { id: 254, title: 'Suricata: The Modern Alternative' },
    { id: 255, title: 'Analyzing IDS Alerts' },
    { id: 256, title: 'Final Quiz' }
];

const lessons = {
    251: {
        content: `# IDS Types: NIDS vs HIDS

**IDS (Intrusion Detection System)** monitors for malicious activity and alerts you.

## NIDS (Network-Based IDS)
Monitors network traffic by tapping into the wire.
*   **Where**: Placed at network choke points (behind the firewall, in front of the DMZ).
*   **What it sees**: Packet headers, payloads, connections.
*   **Examples**: Snort, Suricata, Zeek.
*   **Strength**: Sees everything on the network.
*   **Weakness**: Blind to encrypted traffic (HTTPS/TLS) unless you decrypt it.

## HIDS (Host-Based IDS)
Monitors activity on a single host (server/laptop).
*   **What it sees**: File changes, login attempts, process execution, system calls.
*   **Examples**: OSSEC, Wazuh Agent, Sysmon.
*   **Strength**: Can see inside encrypted sessions (the data is decrypted on the host).
*   **Weakness**: Must be installed on every machine.`,
        questions: [
            ['Where is a NIDS typically deployed?', 'At network choke points (e.g., behind firewall)', 'Network edge', ['On each laptop', 'At network choke points (e.g., behind firewall)', 'In the cloud only', 'On the router console']],
            ['What is a major weakness of NIDS?', 'Blind to encrypted traffic (TLS)', 'Encryption', ['It is slow', 'Blind to encrypted traffic (TLS)', 'It needs batteries', 'It cannot see packets']],
            ['Which tool is a common HIDS agent?', 'OSSEC / Wazuh', 'Host agent', ['Snort', 'OSSEC / Wazuh', 'Wireshark', 'Nmap']]
        ]
    },
    252: {
        content: `# Signature vs Anomaly Detection

## Signature-Based Detection
"I know what bad looks like."
*   **How**: Uses a database of known attack patterns (signatures/rules).
*   **Example Rule**: \`IF packet contains "rm -rf /"\` -> \`ALERT: Destructive Command\`.
*   **Pros**: Low false positives (very accurate for known threats).
*   **Cons**: Cannot detect Zero-Day attacks (new, unknown threats).

## Anomaly-Based Detection
"I know what normal looks like."
*   **How**: Learns a baseline of "normal" traffic/behavior. Anything outside is flagged.
*   **Example**: "Normally, this server sends 10 MB/day. Today it sent 10 GB." -> \`ALERT: Data Exfiltration?\`
*   **Pros**: Can detect novel attacks (Zero-Days).
*   **Cons**: High false positives. Legitimate changes (new app, new user) can trigger alerts.

## Hybrid Approach
Modern IDS tools use both methods together.`,
        questions: [
            ['What is the main weakness of Signature-Based detection?', 'Cannot detect Zero-Day (unknown) attacks', 'New threats', ['Too many alerts', 'Cannot detect Zero-Day (unknown) attacks', 'It is expensive', 'It requires hardware']],
            ['Anomaly-Based detection learns a _____ of normal behavior.', 'Baseline', 'Normal', ['Signature', 'Baseline', 'Firewall', 'Password']],
            ['Which method typically has more False Positives?', 'Anomaly-Based', 'Noisy', ['Signature-Based', 'Anomaly-Based', 'Neither', 'Both equally']]
        ]
    },
    253: {
        content: `# Snort: The Open-Source IDS

**Snort** is the most famous open-source IDS. It was acquired by Cisco.

## Snort Rule Structure
A Snort rule has two parts: **Header** and **Options**.
\`\`\`
alert tcp any any -> any 80 (msg:"HTTP Traffic"; sid:1000001;)
\`\`\`
*   **Action**: \`alert\` (log and alert).
*   **Protocol**: \`tcp\`.
*   **Source**: \`any any\` (any IP, any port).
*   **Direction**: \`->\` (from source to destination).
*   **Destination**: \`any 80\` (any IP, port 80).
*   **Options**: \`msg\` (message), \`sid\` (signature ID).

## Simple Detection Rule
\`\`\`
alert tcp $EXTERNAL_NET any -> $HOME_NET 22 (msg:"SSH Brute Force Attempt"; threshold:type both, track by_src, count 5, seconds 60; sid:1000002;)
\`\`\`
*   This alerts if an external IP tries to connect to port 22 (SSH) more than 5 times in 60 seconds.`,
        questions: [
            ['In a Snort rule, what does "sid" stand for?', 'Signature ID', 'Unique ID', ['Session ID', 'Signature ID', 'Source ID', 'Snort ID']],
            ['What action does "alert" perform in Snort?', 'Logs and generates an alert', 'Notify', ['Blocks traffic', 'Logs and generates an alert', 'Drops the packet', 'Ignores it']],
            ['What symbol defines direction in Snort rules?', '-> (Arrow)', 'Arrow', ['<-', '-> (Arrow)', '==', '=>']]
        ]
    },
    254: {
        content: `# Suricata: The Modern Alternative

**Suricata** is a high-performance IDS/IPS developed by the Open Information Security Foundation (OISF).

## Suricata vs Snort
| Feature | Snort | Suricata |
|---------|-------|----------|
| Multi-threading | Snort 2: No, Snort 3: Yes | Yes (Native) |
| Protocol Detection | Basic | Advanced (HTTP, TLS, DNS parsing) |
| Rule Compatibility | Snort Rules Only | Snort Rules + Suricata Rules |
| Lua Scripting | Limited | Full Support |

## Key Features
*   **Multi-threaded**: Uses all your CPU cores. Much faster on modern hardware.
*   **Protocol Parsing**: Automatically extracts fields from HTTP headers, TLS certs, DNS queries.
*   **File Extraction**: Can save suspicious files from network traffic for analysis.

## Example Suricata Rule
\`\`\`
alert http any any -> any any (msg:"Malicious User-Agent"; http.user_agent; content:"Cobalt Strike"; sid:2000001; rev:1;)
\`\`\`
*   Detects HTTP traffic with a User-Agent containing "Cobalt Strike" (common C2 framework).`,
        questions: [
            ['What is a major performance advantage of Suricata over Snort 2?', 'Multi-threading (uses all CPU cores)', 'Parallel', ['It is smaller', 'Multi-threading (uses all CPU cores)', 'It has a GUI', 'It is older']],
            ['Can Suricata use Snort rules?', 'Yes', 'Compatible', ['No', 'Yes', 'Only some', 'Only paid']],
            ['What does Suricata\'s "File Extraction" feature do?', 'Saves suspicious files from network traffic', 'Carving', ['Deletes files', 'Saves suspicious files from network traffic', 'Encrypts files', 'Compresses files']]
        ]
    },
    255: {
        content: `# Analyzing IDS Alerts

When you get an IDS alert, don't just blindly escalate. **Investigate**.

## Triage Workflow
1.  **Read the Alert Message**: What does the rule claim happened?
2.  **Check the Raw Packet/Log**: Does the evidence match the claim? (False Positive check).
3.  **Pivot on Source IP**: Is this IP known bad (TI lookup)? What else did this IP do?
4.  **Pivot on Internal Host**: Is the victim machine already compromised? Check EDR.
5.  **Make a Decision**: True Positive -> Escalate. False Positive -> Tune the rule.

## Common False Positive Causes
*   **Security Scanners**: Your own Nessus scanner triggering "Port Scan" alerts.
*   **Development Activity**: Developers testing payloads in a lab.
*   **Overly Broad Rules**: A rule that alerts on "any outbound connection".

## Tuning
If an alert is noisy but the rule is still valuable:
*   **Whitelist**: Exclude specific source IPs (e.g., the scanner).
*   **Threshold**: Only alert if it happens > X times.`,
        questions: [
            ['What is the first step when triaging an IDS alert?', 'Read the alert message to understand the claim', 'Understand', ['Delete it', 'Read the alert message to understand the claim', 'Block the IP', 'Reboot the server']],
            ['What often causes False Positives from internal security scanners?', 'Scanners like Nessus trigger "Port Scan" rules', 'Your own tools', ['Hackers', 'Scanners like Nessus trigger "Port Scan" rules', 'Viruses', 'Weather']],
            ['What is "Tuning" an IDS rule?', 'Adjusting it to reduce false positives', 'Improve accuracy', ['Deleting the rule', 'Adjusting it to reduce false positives', 'Making it louder', 'Breaking it']]
        ]
    },
    256: {
        content: `# Final Quiz

Test your knowledge of Intrusion Detection Systems.`,
        questions: [
            // Types
            ['Which IDS type monitors network traffic at a choke point?', 'NIDS', 'Network', ['HIDS', 'NIDS', 'SIDS', 'AIDS']],
            ['Which IDS type can see inside encrypted sessions on the host?', 'HIDS', 'Host', ['NIDS', 'HIDS', 'Firewall', 'VPN']],
            
            // Detection Methods
            ['Signature-Based detection relies on:', 'A database of known attack patterns', 'Signatures', ['Learning normal behavior', 'A database of known attack patterns', 'User reports', 'Random chance']],
            ['Anomaly-Based detection can find:', 'Zero-Day attacks', 'Novel threats', ['Only known attacks', 'Zero-Day attacks', 'Nothing', 'Old malware']],
            
            // Tools
            ['Which tool is native multi-threaded?', 'Suricata', 'Performance', ['Snort 2', 'Suricata', 'Wireshark', 'Nmap']],
            ['In Snort, what does "msg" specify?', 'The alert message text', 'Description', ['Source IP', 'The alert message text', 'Destination port', 'Protocol']]
        ]
    }
};

async function createModule25() {
    try {
        console.log('🚀 Creating Module 25: Intrusion Detection...\n');

        console.log(`Processing Module ${overview.id}: ${overview.title}`);
        await db.query(`INSERT INTO modules (id, title, description, display_order, learning_path_id) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), description = VALUES(description), learning_path_id = VALUES(learning_path_id)`, 
            [overview.id, overview.title, overview.description, 25, overview.learning_path_id]);

        for (const t of tasks) {
            await db.query(`INSERT INTO tasks (id, module_id, title, is_active, display_order) VALUES (?, ?, ?, 1, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }

        let totalLessons = 0;
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);

            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 15]);

            for (let j = 0; j < lesson.questions.length; j++) {
                const q = lesson.questions[j];
                const options = q[3] ? JSON.stringify(q[3]) : null;
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, options, case_sensitive) VALUES (?, ?, ?, ?, ?, ?, ?)',
                    [taskId, q[0], q[1], j + 1, q[2], options, 0]);
            }
            totalLessons++;
        }

        console.log(`\n✅ Module 25 (Intrusion Detection) Created! (${totalLessons} lessons)\n`);
        process.exit(0);

    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createModule25();
