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

const overview = {
    id: 27,
    title: 'Incident Response Framework',
    description: 'Master the structured approach to handling security incidents.',
    learning_path_id: 4
};

const tasks = [
    { id: 271, title: 'What is Incident Response?' },
    { id: 272, title: 'The IR Lifecycle (NIST)' },
    { id: 273, title: 'Phase 1: Preparation' },
    { id: 274, title: 'Phase 2: Detection & Analysis' },
    { id: 275, title: 'Phase 3: Containment' },
    { id: 276, title: 'Phase 4: Eradication & Recovery' },
    { id: 277, title: 'Phase 5: Post-Incident Activity' },
    { id: 278, title: 'Final Quiz' }
];

const lessons = {
    271: {
        content: `# What is Incident Response?

**Incident Response (IR)** is the organized approach to addressing and managing the aftermath of a security breach or cyberattack.

## Why is IR Important?
*   **Speed**: The faster you respond, the less damage.
*   **Consistency**: A documented process avoids chaos during a crisis.
*   **Compliance**: Many regulations (PCI-DSS, HIPAA) require an IR plan.

## What is an "Incident"?
Any event that threatens the confidentiality, integrity, or availability of information.
*   **Examples**: Malware infection, data breach, DDoS attack, phishing compromise, insider threat.

## The IR Team (CSIRT)
**CSIRT (Computer Security Incident Response Team)** members:
*   **IR Lead**: Coordinates the response.
*   **SOC Analysts**: Detect and investigate.
*   **Forensics Specialist**: Collects evidence.
*   **IT/Sysadmin**: Implements containment.
*   **Legal/PR**: Handles external communication.`,
        questions: [
            ['What does CSIRT stand for?', 'Computer Security Incident Response Team', 'Team', ['Cyber Security Internal Review Team', 'Computer Security Incident Response Team', 'Critical System IR Team', 'Cloud Security IR Task']],
            ['Why is a documented IR process important?', 'It ensures consistent and fast response', 'Consistency', ['It looks good', 'It ensures consistent and fast response', 'It is optional', 'It slows things down']],
            ['Which of these is an example of a security incident?', 'Malware infection', 'Breach', ['Password reset', 'Malware infection', 'Software update', 'New employee onboarding']]
        ]
    },
    272: {
        content: `# The IR Lifecycle (NIST)

The **NIST SP 800-61** framework defines the standard IR lifecycle.

## The 4 Phases
\`\`\`
┌────────────────────────────────────────────────┐
│  1. Preparation                                │
├────────────────────────────────────────────────┤
│  2. Detection & Analysis                       │
├────────────────────────────────────────────────┤
│  3. Containment, Eradication & Recovery        │
├────────────────────────────────────────────────┤
│  4. Post-Incident Activity (Lessons Learned)   │
└────────────────────────────────────────────────┘
\`\`\`

## It's a Cycle, Not a Line
After "Lessons Learned", you loop back to "Preparation" to improve.

## Alternative: SANS 6-Step Model
1.  Preparation
2.  Identification
3.  Containment
4.  Eradication
5.  Recovery
6.  Lessons Learned

*NIST and SANS are essentially the same, just organized differently.*`,
        questions: [
            ['How many phases are in the NIST IR lifecycle?', '4', 'Four', ['3', '4', '5', '6']],
            ['Which phase comes after "Detection & Analysis"?', 'Containment, Eradication & Recovery', 'Next', ['Preparation', 'Containment, Eradication & Recovery', 'Post-Incident', 'None']],
            ['What happens after "Lessons Learned"?', 'Loop back to Preparation (improvement)', 'Cycle', ['Nothing', 'Loop back to Preparation (improvement)', 'Delete everything', 'Close the case']]
        ]
    },
    273: {
        content: `# Phase 1: Preparation

**You cannot respond to an incident if you are not prepared.**

## Key Preparation Activities
1.  **Build the Team**: Identify CSIRT members, backups, and contact lists.
2.  **Create Playbooks**: Step-by-step guides for common incidents (ransomware, phishing, etc.).
3.  **Deploy Tools**: EDR, SIEM, Forensic workstations, ticketing system.
4.  **Baseline Systems**: Know what "normal" looks like (open ports, running services).
5.  **Train the Team**: Tabletop exercises, simulations.

## The IR Plan Document
*   **Scope**: What is considered an incident?
*   **Roles**: Who does what?
*   **Escalation**: When to involve management, legal, law enforcement?
*   **Communication**: Who talks to the press?

## Jump Bag / Go Bag
A pre-packed kit with forensic tools (write blockers, USB drives, cables, laptop) for on-site response.`,
        questions: [
            ['What is a "Playbook" in IR context?', 'A step-by-step guide for handling specific incidents', 'Runbook', ['A video game', 'A step-by-step guide for handling specific incidents', 'A backup plan', 'A training manual']],
            ['What is a "Jump Bag"?', 'Pre-packed forensic tools for on-site response', 'Go Bag', ['A travel bag', 'Pre-packed forensic tools for on-site response', 'A backup drive', 'A parachute']],
            ['Why is "Baselining" systems important?', 'To know what normal looks like', 'Comparison', ['It is not', 'To know what normal looks like', 'To delete old files', 'To upgrade software']]
        ]
    },
    274: {
        content: `# Phase 2: Detection & Analysis

**Identify that an incident is occurring and understand its scope.**

## Detection Sources
*   **SIEM Alerts**: Correlation rules trigger.
*   **EDR Alerts**: Suspicious process behavior.
*   **User Reports**: "My computer is acting strange."
*   **External Notification**: FBI calls, vendor notification.
*   **Threat Intelligence**: New IOCs match your logs.

## Initial Analysis (Triage)
1.  **Validate**: Is this a True Positive or False Positive?
2.  **Scope**: How many systems are affected?
3.  **Severity**: What is the business impact?
4.  **Classification**: What type of incident? (Malware, Phishing, Data Breach)

## Documentation
Start a timeline from the first sign of compromise.
*   *10:00 - Alert triggered*
*   *10:15 - Analyst confirmed malware*
*   *10:30 - 3 more hosts identified*`,
        questions: [
            ['What is the first step in analysis?', 'Validate if it is a True Positive', 'Confirm', ['Delete the alert', 'Validate if it is a True Positive', 'Call the police', 'Ignore it']],
            ['What should you start documenting immediately?', 'A timeline of events', 'Timeline', ['A blog post', 'A timeline of events', 'A resignation letter', 'A shopping list']],
            ['Who might notify you of an incident externally?', 'FBI, vendor, or partner', 'External', ['The janitor', 'FBI, vendor, or partner', 'The intern', 'Nobody']]
        ]
    },
    275: {
        content: `# Phase 3: Containment

**Stop the bleeding. Limit the damage.**

## Containment Strategies
1.  **Short-Term Containment**: Immediate actions.
    *   Isolate the infected host from the network.
    *   Disable compromised user accounts.
    *   Block malicious IPs/domains at the firewall.
2.  **Long-Term Containment**: Sustainable until eradication.
    *   Move affected systems to a quarantine VLAN.
    *   Apply temporary patches or workarounds.

## Key Decisions
*   **Preserve Evidence vs Stop Attack?**: If you wipe the machine, you lose forensic evidence.
*   **When to involve Law Enforcement?**: If criminal activity, consider FBI/local police.

## Common Mistakes
*   ❌ Alerting the attacker by changing passwords too early (they may have persistence).
*   ❌ Shutting down a machine (volatile memory is lost).
*   ✅ Isolate the network, but keep the machine running for forensics.`,
        questions: [
            ['What is "Short-Term Containment"?', 'Immediate actions to stop the attack', 'Quick fix', ['Long-term planning', 'Immediate actions to stop the attack', 'Deleting files', 'Rebooting']],
            ['Why should you NOT shut down a compromised machine immediately?', 'Volatile memory (RAM) evidence is lost', 'Forensics', ['It is faster', 'Volatile memory (RAM) evidence is lost', 'It makes noise', 'It uses electricity']],
            ['What is a quarantine VLAN used for?', 'Isolating compromised systems while keeping them accessible', 'Isolation', ['Gaming', 'Isolating compromised systems while keeping them accessible', 'Faster internet', 'Printer sharing']]
        ]
    },
    276: {
        content: `# Phase 4: Eradication & Recovery

## Eradication
**Remove the threat completely.**
*   Delete malware files.
*   Remove persistence mechanisms (registry keys, scheduled tasks).
*   Patch the vulnerability that was exploited.
*   Reset compromised credentials.

## Recovery
**Restore normal operations.**
1.  **Rebuild or restore** affected systems from clean backups.
2.  **Validate** the systems are clean before reconnecting.
3.  **Monitor closely** for signs of re-infection.
4.  **Gradual reconnection**: Don't bring everything back at once.

## Validation Checklist
*   ☐ Malware removed?
*   ☐ Backdoors closed?
*   ☐ Passwords reset?
*   ☐ Patches applied?
*   ☐ Logs reviewed for re-infection?`,
        questions: [
            ['What must be removed during Eradication?', 'Malware and persistence mechanisms', 'Cleanup', ['User files', 'Malware and persistence mechanisms', 'Operating system', 'All software']],
            ['Before reconnecting a recovered system, what should you do?', 'Validate it is clean', 'Verify', ['Just plug it in', 'Validate it is clean', 'Delete everything', 'Ignore it']],
            ['Why "gradual reconnection"?', 'To detect re-infection before spreading', 'Careful', ['It is slower', 'To detect re-infection before spreading', 'To save power', 'It looks professional']]
        ]
    },
    277: {
        content: `# Phase 5: Post-Incident Activity

**Learn from the incident to prevent recurrence.**

## Lessons Learned Meeting
Hold within 1-2 weeks of incident closure.
*   **What happened?** (Root Cause Analysis)
*   **What went well?**
*   **What could be improved?**
*   **Action Items**: Who will fix what, by when?

## Incident Report
A formal document containing:
*   Executive Summary
*   Timeline of Events
*   Technical Details
*   Business Impact
*   Recommendations

## Updating Defenses
*   Add new IOCs to blocklists.
*   Update SIEM rules to detect similar attacks.
*   Improve playbooks based on experience.
*   Train staff on new threats.`,
        questions: [
            ['When should the Lessons Learned meeting be held?', 'Within 1-2 weeks of incident closure', 'Soon', ['Never', 'Within 1-2 weeks of incident closure', 'After 1 year', 'During the incident']],
            ['What is the purpose of a Post-Incident Report?', 'Document what happened and recommendations', 'Documentation', ['To blame someone', 'Document what happened and recommendations', 'To close the ticket', 'To delete logs']],
            ['How do you prevent similar incidents?', 'Update SIEM rules, playbooks, and train staff', 'Improve', ['Ignore it', 'Update SIEM rules, playbooks, and train staff', 'Fire everyone', 'Do nothing']]
        ]
    },
    278: {
        content: `# Final Quiz

Test your knowledge of the Incident Response lifecycle.`,
        questions: [
            ['Which framework defines the 4-phase IR lifecycle?', 'NIST SP 800-61', 'Standard', ['ISO 27001', 'NIST SP 800-61', 'PCI DSS', 'HIPAA']],
            ['What is the first phase of IR?', 'Preparation', 'First', ['Detection', 'Preparation', 'Containment', 'Recovery']],
            ['Isolating a host from the network is part of which phase?', 'Containment', 'Isolate', ['Preparation', 'Detection', 'Containment', 'Eradication']],
            ['Why preserve volatile memory (RAM)?', 'It contains forensic evidence lost on shutdown', 'Evidence', ['It is faster', 'It contains forensic evidence lost on shutdown', 'It is pretty', 'No reason']],
            ['What document guides response to specific incident types?', 'Playbook', 'Runbook', ['Resume', 'Playbook', 'Novel', 'Menu']],
            ['What happens in the "Post-Incident" phase?', 'Lessons Learned and improvement', 'Review', ['Panic', 'Lessons Learned and improvement', 'Vacation', 'Nothing']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 27: Incident Response Framework...\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 27 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
