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

const overview = {
    id: 33,
    title: 'Security Automation',
    description: 'Learn to automate security tasks using SOAR and scripting.',
    learning_path_id: 4
};

const tasks = [
    { id: 331, title: 'Why Automate Security?' },
    { id: 332, title: 'SOAR Platforms Overview' },
    { id: 333, title: 'Playbook Design Principles' },
    { id: 334, title: 'Common Automation Use Cases' },
    { id: 335, title: 'Python for Security Automation' },
    { id: 336, title: 'Final Quiz' }
];

const lessons = {
    331: {
        content: `# Why Automate Security?

**Security teams are overwhelmed.** Automation is the solution.

## The Problem
*   **Alert Fatigue**: SOC analysts see thousands of alerts daily.
*   **Skill Shortage**: Not enough qualified analysts.
*   **Speed**: Attackers move in minutes; humans take hours.
*   **Repetitive Tasks**: Many tasks are the same every time.

## The Solution: Automation
*   **Faster Response**: Scripts run in seconds.
*   **Consistency**: Same process every time, no human error.
*   **Scale**: Handle 10x the workload.
*   **Analyst Focus**: Free analysts for complex investigations.

## What to Automate
*   **Enrichment**: Look up IP reputation, hash on VirusTotal.
*   **Triage**: Auto-close known false positives.
*   **Containment**: Isolate host, block IP.
*   **Ticketing**: Create incidents automatically.`,
        questions: [
            ['What is "Alert Fatigue"?', 'Being overwhelmed by too many alerts', 'Tired', ['Being lazy', 'Being overwhelmed by too many alerts', 'Not seeing alerts', 'Fast response']],
            ['Automation provides what key benefit?', 'Speed and consistency', 'Fast', ['More alerts', 'Speed and consistency', 'More cost', 'Complexity']],
            ['Which task is ideal for automation?', 'Repetitive enrichment lookups', 'Repetitive', ['Complex investigations', 'Repetitive enrichment lookups', 'Board meetings', 'Hiring']]
        ]
    },
    332: {
        content: `# SOAR Platforms Overview

**SOAR (Security Orchestration, Automation, and Response)** platforms coordinate automated security workflows.

## Key Capabilities
1.  **Orchestration**: Connect different tools (SIEM, EDR, Firewall, Ticketing).
2.  **Automation**: Execute playbooks without human intervention.
3.  **Response**: Take actions (block, isolate, notify).
4.  **Case Management**: Track incidents from detection to closure.

## Leading SOAR Platforms
| Platform | Vendor |
|----------|--------|
| Splunk SOAR (Phantom) | Splunk |
| Microsoft Sentinel | Microsoft |
| Cortex XSOAR | Palo Alto |
| IBM Resilient | IBM |
| TheHive + Cortex | Open Source |
| Shuffle | Open Source |

## Integration is Key
*   SOAR's value comes from connecting your tools.
*   API integrations with SIEM, EDR, Threat Intel, Ticketing.`,
        questions: [
            ['What does SOAR stand for?', 'Security Orchestration, Automation, and Response', 'SOAR', ['Security Operations and Response', 'Security Orchestration, Automation, and Response', 'System Organized Auto Response', 'None']],
            ['Which is an open-source SOAR platform?', 'TheHive / Shuffle', 'Free', ['Splunk SOAR', 'TheHive / Shuffle', 'Cortex XSOAR', 'IBM Resilient']],
            ['SOAR connects tools through:', 'API integrations', 'APIs', ['Email', 'API integrations', 'Phone calls', 'Fax']]
        ]
    },
    333: {
        content: `# Playbook Design Principles

**Playbooks are automated workflows for specific scenarios.**

## Structure of a Playbook
1.  **Trigger**: What starts the playbook? (e.g., SIEM alert)
2.  **Enrichment**: Gather context (IP lookup, user info).
3.  **Decision**: Is this malicious? (Human or automated decision).
4.  **Action**: Respond (block, isolate, notify).
5.  **Closure**: Update ticket, document findings.

## Design Best Practices
*   **Start Simple**: Automate one small task first.
*   **Human in the Loop**: For critical actions, require approval.
*   **Logging**: Log every action for audit trail.
*   **Error Handling**: What happens if an API call fails?
*   **Testing**: Test in a lab before production.

## Example: Phishing Playbook
1.  User reports phishing email.
2.  Extract URLs, attachments.
3.  Check URLs against threat intel.
4.  If malicious: Block sender, delete emails from all mailboxes.
5.  Notify user, close ticket.`,
        questions: [
            ['What is the first step in a playbook?', 'Trigger (what starts the workflow)', 'Start', ['Action', 'Trigger (what starts the workflow)', 'Closure', 'Enrichment']],
            ['Why include "Human in the Loop"?', 'For critical actions requiring approval', 'Safety', ['Slower', 'For critical actions requiring approval', 'More errors', 'Fun']],
            ['What should playbooks always include?', 'Logging and error handling', 'Audit', ['Music', 'Logging and error handling', 'Colors', 'Animations']]
        ]
    },
    334: {
        content: `# Common Automation Use Cases

## 1. Phishing Response
*   Extract IOCs from reported email.
*   Check against threat intel.
*   Block sender, delete from mailboxes.
*   Notify user.

## 2. Malware Alert Triage
*   Get alert from EDR.
*   Check hash on VirusTotal.
*   Look up host info (owner, criticality).
*   If malicious: Isolate host, create ticket.

## 3. Threat Intel Ingestion
*   Receive IOC feed.
*   Parse and normalize.
*   Push to SIEM/Firewall blocklists.

## 4. User Account Compromise
*   Detect suspicious login (impossible travel).
*   Force password reset.
*   Revoke active sessions.
*   Notify user and manager.

## 5. Vulnerability Patching
*   New CVE published.
*   Scan assets for vulnerability.
*   Create tickets for affected systems.`,
        questions: [
            ['What action is common for malware alerts?', 'Isolate the host', 'Containment', ['Delete the host', 'Isolate the host', 'Ignore', 'Promote user']],
            ['Threat Intel automation pushes IOCs to:', 'SIEM and Firewall blocklists', 'Block', ['Email', 'SIEM and Firewall blocklists', 'Phone', 'Printer']],
            ['For suspected account compromise, what should be automated?', 'Force password reset and revoke sessions', 'Reset', ['Promote user', 'Force password reset and revoke sessions', 'Delete account', 'Ignore']]
        ]
    },
    335: {
        content: `# Python for Security Automation

**Python is the go-to language for security automation.**

## Why Python?
*   Simple, readable syntax.
*   Huge library ecosystem.
*   Great for API interactions.
*   Widely used in security tools.

## Useful Libraries
| Library | Purpose |
|---------|---------|
| \`requests\` | HTTP calls (REST APIs) |
| \`json\` | Parse/create JSON |
| \`re\` | Regular expressions |
| \`socket\` | Network connections |
| \`hashlib\` | Calculate file hashes |
| \`pandas\` | Data analysis |
| \`pymisp\` | MISP Threat Intel |
| \`virustotal-python\` | VirusTotal API |

## Example: VirusTotal Hash Lookup
\`\`\`python
import requests

API_KEY = "your_api_key"
file_hash = "abc123..."

url = f"https://www.virustotal.com/api/v3/files/{file_hash}"
headers = {"x-apikey": API_KEY}
response = requests.get(url, headers=headers)
print(response.json())
\`\`\``,
        questions: [
            ['Which Python library is used for HTTP calls?', 'requests', 'HTTP', ['json', 'requests', 'socket', 'hashlib']],
            ['Why is Python popular for security?', 'Simple syntax and great libraries', 'Easy', ['It is fast', 'Simple syntax and great libraries', 'It is new', 'It is hard']],
            ['What does hashlib calculate?', 'File hashes (MD5, SHA256)', 'Hash', ['Passwords', 'File hashes (MD5, SHA256)', 'Colors', 'Sound']]
        ]
    },
    336: {
        content: `# Final Quiz

Test your Security Automation knowledge.`,
        questions: [
            ['SOAR stands for:', 'Security Orchestration, Automation, and Response', 'SOAR', ['Security Operations', 'Security Orchestration, Automation, and Response', 'System Order', 'None']],
            ['What is the main benefit of automation?', 'Speed and consistency', 'Faster', ['More alerts', 'Speed and consistency', 'More cost', 'Complexity']],
            ['What starts a playbook?', 'A trigger (e.g., SIEM alert)', 'Trigger', ['A human', 'A trigger (e.g., SIEM alert)', 'Random chance', 'Nothing']],
            ['Which Python library makes HTTP API calls?', 'requests', 'Library', ['json', 'requests', 'socket', 'os']],
            ['For malware alerts, a common automated action is:', 'Isolate the host', 'Contain', ['Delete files', 'Isolate the host', 'Reboot', 'Ignore']],
            ['TheHive is an example of:', 'Open-source SOAR', 'Free', ['Commercial SIEM', 'Open-source SOAR', 'Antivirus', 'Firewall']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 33: Security Automation...\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, overview.id, 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), module_id = VALUES(module_id), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }
        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]);
            }
        }
        console.log(`✅ Module 33 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
