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

const overview = {
    id: 22,
    title: 'SIEM Fundamentals',
    description: 'Master the "Brain" of the SOC: Security Information and Event Management.',
    learning_path_id: 3 // SOC Analyst Level 1
};

const tasks = [
    { id: 221, title: 'What is a SIEM?' },
    { id: 222, title: 'Log Sources & Ingestion' },
    { id: 223, title: 'Normalization & Parsing' },
    { id: 224, title: 'Correlation Rules (The Magic)' },
    { id: 225, title: 'Market Leaders: Splunk vs Sentinel' },
    { id: 226, title: 'Open Source: The ELK Stack' },
    { id: 227, title: 'Wazuh: The Modern Open SIEM' },
    { id: 228, title: 'Final Quiz' }
];

const lessons = {
    221: {
        content: `# What is a SIEM?

**SIEM (Security Information and Event Management)** is the centralized brain of a Security Operations Center (SOC).

## The Problem: Data Overload
A typical company generates **millions** of logs per day.
*   Firewalls (Network traffic)
*   Windows Servers (Login events)
*   Antivirus (Malware blocks)
*   Cloud Services (AWS attempts)

You cannot check these manually.

## The Solution: SIEM
The SIEM does three main things:
1.  **Aggregation**: Collects logs from *everywhere* into one pile.
2.  **Correlation**: Connects the dots. "User A logged in from USA, then 5 seconds later User A logged in from Russia." -> **ALERT!**
3.  **Retention**: Stores logs for 1 year+ for compliance (PCI-DSS, HIPAA).

## Key Components
*   **Collector/Forwarder**: The agent installed on the endpoint to send logs.
*   **Indexer/Database**: Where the massive data is stored (Elasticsearch, Splunk Index).
*   **Visualizer**: The UI for the analyst (Kibana, Splunk Search Head).`,
        questions: [
            ['What is the primary function of "Correlation" in a SIEM?', 'Connecting related events to detect threats', 'Connecting dots', ['Saving storage space', 'Connecting related events to detect threats', 'Deleting old logs', 'Speeding up the network']],
            ['Why is "Retention" important?', 'Compliance and Forensic Investigation', 'History', ['To fill up hard drives', 'Compliance and Forensic Investigation', 'To slow down the system', 'It is not important']],
            ['What component typically sits on the Endpoint to send logs?', 'Forwarder / Agent', 'Sender', ['Firewall', 'Forwarder / Agent', 'Router', 'Switch']]
        ]
    },
    222: {
        content: `# Log Sources & Ingestion

Garbage In, Garbage Out. A SIEM is only as good as the data you feed it.

## Common Log Sources
1.  **Syslog (UDP 514)**: The standard for Linux, Routers, and Firewalls. It's fast but unrelated (fire-and-forget).
2.  **Windows Event Logs**: Structured logs from Windows (Security.evtx, System.evtx). Harder to parse than Syslog.
3.  **API Integration**: Pulling logs from Cloud (AWS CloudTrail, Office 365 Audit Logs).
4.  **Flow Data (NetFlow)**: Captures "Who talked to Whom", but not the content (packet body).

## The Noise Problem
You don't want *every* log.
*   **Bad**: Enabling "Success Auditing" for every file access on a File Server. (Billions of logs).
*   **Good**: Logging Failed Logins, Process Creations, and Firewall Drops.

## Ingestion Challenges
*   **Time Zones**: The Firewall is UTC, the Server is EST. The SIEM must align them.
*   **Bandwidth**: Sending 1TB of logs per day can kill a network link.`,
        questions: [
            ['Which protocol is the standard for network device logging?', 'Syslog', 'Standard', ['SMB', 'Syslog', 'FTP', 'HTTP']],
            ['What is "NetFlow" data?', 'Traffic metadata (Who talked to Whom)', 'Traffic info', ['Full packet capture', 'Traffic metadata (Who talked to Whom)', 'Email contents', 'File contents']],
            ['Why is "Time Zone" alignment critical in SIEM?', 'To accurately correlate events across the world', 'Timeline', ['It isn\'t', 'To accurately correlate events across the world', 'To know when to eat lunch', 'For daylight savings']]
        ]
    },
    223: {
        content: `# Normalization & Parsing

Raw logs are ugly and inconsistent.
*   **Cisco Router**: \`Oct 12 10:00:00 1.2.3.4 %SEC-1-DENY ...\`
*   **Windows**: \`EventID: 4625, Account: Bob ...\`

## What is Normalization?
Converting different log formats into a **Single Standard Format**.

### The Field Map
*   Cisco calls the user \`src_user\`.
*   Windows calls the user \`AccountName\`.
*   **SIEM Field**: \`user.name\`

When you search \`user.name="Bob"\`, the SIEM looks at *both* Cisco and Windows logs automatically because they are mapped to the same field.

## Parsing
The process of extracting specific data from a raw text line.
*   *Raw*: \`Failed password for root from 192.168.1.1\`
*   *Parsed*:
    *   Action: Failed Login
    *   User: root
    *   Src_IP: 192.168.1.1`,
        questions: [
            ['What is the goal of "Normalization"?', 'Converting mixed formats into a standard field structure', 'Standardization', ['Deleting logs', 'Converting mixed formats into a standard field structure', 'Encrypting logs', 'Compressing logs']],
            ['If Windows calls it "AccountName" and Linux calls it "User", what does the SIEM do?', 'Maps them to a single field like user.name', 'Mapping', ['Ignores them', 'Maps them to a single field like user.name', 'Deletes one', 'Errors out']],
            ['What process extracts "192.168.1.1" from a raw text message?', 'Parsing', 'Extraction', ['Hashing', 'Parsing', 'Encryption', 'Routing']]
        ]
    },
    224: {
        content: `# Correlation Rules (The Magic)

This is why we pay thousands of dollars for a SIEM.

## The Logic
A rule is a logic statement: \`IF [Condition A] AND [Condition B] THEN [Alert]\`.

### Example 1: Brute Force
*   **Logic**: IF (Event="Failed Login") happens > 10 times in 1 minute with same (User) or (Source IP).
*   **Output**: "Potential Brute Force Detected".

### Example 2: Impossible Travel
*   **Logic**: IF (Successful Login from Country A) AND (Successful Login from Country B) happening within < 2 hours.
*   **Context**: Distance between A and B is > 500 miles.

## Tuning
Rules generate **False Positives**.
*   *Alert*: "Brute Force Detected".
*   *Reality*: An admin forgot his password and tried 5 times.
*   *Tuning*: Whitelist the admin's IP? Or increase the threshold to 20 attempts?`,
        questions: [
            ['What defines a "Brute Force" correlation rule?', 'Multiple failed logins in a short time', 'Many fails', ['One failed login', 'Multiple failed logins in a short time', 'A successful login', 'A slow login']],
            ['What is "Impossible Travel"?', 'Logins from two distant locations in an impossibly short time', 'Teleportation', ['Traveling without a visa', 'Logins from two distant locations in an impossibly short time', 'VPN usage', 'Remote work']],
            ['Adjusting a rule to reduce False Positives is called:', 'Tuning', 'Adjustment', ['Breaking', 'Tuning', 'Deleting', 'Ignoring']]
        ]
    },
    225: {
        content: `# Market Leaders: Splunk vs Sentinel

## Splunk
*   **The King**: The biggest name in SIEM.
*   **Language**: **SPL** (Search Processing Language). It is powerful (pipe-based like Linux).
    *   \`index=firewall | stats count by src_ip\`
*   **Pros**: Massive ecosystem, can ingest anything.
*   **Cons**: Extremely expensive (often pay-per-GB).

## Microsoft Sentinel
*   **The Challenger**: Cloud-native (runs in Azure).
*   **Language**: **KQL** (Kusto Query Language). Very fast, SQL-like.
    *   \`FirewallLogs | summarize count() by SrcIP\`
*   **Pros**: Integrated perfectly with Office 365 / Azure AD. No server maintenance (SaaS).
*   **Cons**: Can get expensive if not managed. Tie-in to Microsoft ecosystem.`,
        questions: [
            ['What query language does Splunk use?', 'SPL (Search Processing Language)', 'SPL', ['SQL', 'SPL (Search Processing Language)', 'KQL', 'Python']],
            ['What query language does Microsoft Sentinel use?', 'KQL (Kusto Query Language)', 'Kusto', ['SPL', 'KQL (Kusto Query Language)', 'Bash', 'PowerShell']],
            ['What is a major downside of Splunk traditionally?', 'High cost', 'Expensive', ['It is slow', 'High cost', 'It has no features', 'It only runs on Mac']]
        ]
    },
    226: {
        content: `# Open Source: The ELK Stack

## What is ELK?
A stack of three open-source tools managed by Elastic.
1.  **Elasticsearch**: The Database (Search Engine). It stores the JSON logs.
2.  **Logstash**: The Pipeline (Ingestion). It takes raw logs, parses them, and sends them to Elastic.
3.  **Kibana**: The UI (Visualizer). Where you make dashboards and graphs.

## The "E" in SIEM?
ELK alone deals with logs, but it lacks the "Security Logic" (Correlation) out of the box.
*   **Elastic Security**: Newer versions added SIEM features (detection rules).

## Beats
Lightweight agents you install on endpoints.
*   **Winlogbeat**: Sends Windows Events.
*   **Filebeat**: Sends text logs.
*   **Packetbeat**: Network data.`,
        questions: [
            ['Which component of ELK provides the Visualization / Dashboard?', 'Kibana', 'UI', ['Elasticsearch', 'Kibana', 'Logstash', 'Beats']],
            ['What is the Database/Search Engine of the stack?', 'Elasticsearch', 'DB', ['MySQL', 'Elasticsearch', 'Redis', 'Mongo']],
            ['What are "Beats"?', 'Lightweight data shippers/agents', 'Agents', ['Music files', 'Lightweight data shippers/agents', 'Databases', 'Firewalls']]
        ]
    },
    227: {
        content: `# Wazuh: The Modern Open SIEM

**Wazuh** started as a fork of OSSEC (HIDS) but evolved into a full XDR/SIEM platform.

## Why it's popular
1.  **Free/Open Source**: You can run a full SOC for $0 (hardware cost only).
2.  **All-in-One**: It has File Integrity Monitoring (FIM), Vulnerability Detection, and Log Analysis combined.
3.  **The Agent**: The Wazuh Agent is very powerful. It can even take "Active Response" (block an IP) automatically.

## Architecture
*   **Wazuh Manager**: The central server.
*   **Wazuh Indexer**: (Based on OpenSearch/Elasticsearch) stores data.
*   **Wazuh Dashboard**: (Based on Kibana) the UI.`,
        questions: [
            ['What makes Wazuh unique compared to basic ELK?', 'It includes XDR features like FIM and Active Response', 'XDR', ['It costs money', 'It includes XDR features like FIM and Active Response', 'It has no UI', 'It creates viruses']],
            ['What is "Active Response" in Wazuh?', 'The ability to automatically block/stop a threat', 'Action', ['Sending an email', 'The ability to automatically block/stop a threat', 'Deleting the server', 'Calling the police']],
            ['Is Wazuh open source?', 'Yes', 'Free', ['No', 'Yes', 'Only for students', 'It is a subscription']]
        ]
    },
    228: {
        content: `# Module 22 Final Quiz

Test your specific knowledge of SIEM tools and concepts.

*   **Topics**: Normalization, Parsing, Correlation, Splunk, Sentinel, ELK, Wazuh.`,
        questions: [
            // Concepts
            ['What is the "Normalization" phase in SIEM?', 'Mapping different log formats to standard fields', 'Standardize', ['Compressing logs', 'Mapping different log formats to standard fields', 'Deleting logs', 'Encrypting logs']],
            ['Garbage In, Garbage Out refers to:', 'A SIEM is only as good as the log data fed into it', 'Input quality', ['Trash management', 'A SIEM is only as good as the log data fed into it', 'Deleting logs', 'Hardware recycling']],
            ['What is "Impossible Travel"?', 'Logins from two locations physically impossible to traverse in the time', 'Teleportation', ['VPN usage', 'Logins from two locations physically impossible to traverse in the time', 'Dual citizenship', 'Space travel']],
            
            // Tools
            ['SPL (Search Processing Language) belongs to which SIEM?', 'Splunk', 'The big one', ['Sentinel', 'Splunk', 'Wazuh', 'ELK']],
            ['KQL (Kusto Query Language) belongs to which SIEM?', 'Microsoft Sentinel', 'Azure', ['Splunk', 'Microsoft Sentinel', 'QRadar', 'ArcSight']],
            ['Which open-source tool allows for "Active Response" (blocking IPs)?', 'Wazuh', 'XDR', ['Logstash', 'Wazuh', 'Kibana', 'Notepad']],
            
            // Components
            ['In the ELK stack, which tool is the "UI"?', 'Kibana', 'Visualizer', ['Elasticsearch', 'Kibana', 'Logstash', 'Filebeat']],
            ['What does a "Forwarder" do?', 'Sends logs from the endpoint to the SIEM', 'Transportation', ['Stores logs', 'Sends logs from the endpoint to the SIEM', 'Deletes logs', 'Analyzes logs']],
            ['Why do we need "Retention"?', 'Compliance regulations often require keeping logs for 1 year+', 'Compliance', ['To run out of space', 'Compliance regulations often require keeping logs for 1 year+', 'To slow down searches', 'We don\'t']]
        ]
    }
};

async function createModule22() {
    try {
        console.log('🚀 Creating Module 22: SIEM Fundamentals...\n');

        // Create Module (Path 3: SOC Analyst Level 1)
        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, 22, overview.learning_path_id]);

        // Create Tasks
        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;
        // Populate Lessons
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            // Clean
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);

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

            // Insert Questions
            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 22 (SIEM) Created! (${totalLessons} lessons)\n`);
        process.exit(0);

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

createModule22();
