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

const overview = {
    id: 31,
    title: 'MITRE ATT&CK Framework',
    description: 'Understand the knowledge base of adversary tactics and techniques.',
    learning_path_id: 4
};

const tasks = [
    { id: 311, title: 'What is MITRE ATT&CK?' },
    { id: 312, title: 'Tactics: The "Why"' },
    { id: 313, title: 'Techniques: The "How"' },
    { id: 314, title: 'Navigating the Matrix' },
    { id: 315, title: 'Using ATT&CK for Defense' },
    { id: 316, title: 'Final Quiz' }
];

const lessons = {
    311: {
        content: `# What is MITRE ATT&CK?

**MITRE ATT&CK** is a globally-accessible knowledge base of adversary tactics and techniques based on real-world observations.

## Why It Matters
*   **Common Language**: Security teams, vendors, and researchers all use the same terminology.
*   **Gap Analysis**: Identify which techniques you can detect and which you cannot.
*   **Threat Intelligence**: Map threat actors to their known techniques.

## ATT&CK Matrices
*   **Enterprise**: Windows, Linux, macOS, Cloud.
*   **Mobile**: iOS, Android.
*   **ICS**: Industrial Control Systems.

## The Structure
1.  **Tactics**: The adversary's goal (e.g., "Persistence").
2.  **Techniques**: How they achieve the goal (e.g., "Registry Run Keys").
3.  **Sub-Techniques**: More specific methods.
4.  **Procedures**: Real-world examples.`,
        questions: [
            ['What does MITRE ATT&CK provide?', 'Knowledge base of adversary tactics and techniques', 'Framework', ['A firewall', 'Knowledge base of adversary tactics and techniques', 'An antivirus', 'A SIEM']],
            ['What does a "Tactic" represent?', 'The adversary\'s goal', 'Why', ['A specific tool', 'The adversary\'s goal', 'A CVE', 'A patch']],
            ['Which matrix covers Windows, Linux, macOS?', 'Enterprise', 'Main', ['Mobile', 'Enterprise', 'ICS', 'Cloud']]
        ]
    },
    312: {
        content: `# Tactics: The "Why"

**Tactics** are the adversary's tactical objectives - *why* they perform an action.

## The 14 Enterprise Tactics
| Tactic | Goal |
|--------|------|
| Reconnaissance | Gather info on target |
| Resource Development | Build attack infrastructure |
| Initial Access | Get into the network |
| Execution | Run malicious code |
| Persistence | Maintain foothold |
| Privilege Escalation | Get higher permissions |
| Defense Evasion | Avoid detection |
| Credential Access | Steal passwords/tokens |
| Discovery | Learn the environment |
| Lateral Movement | Move to other systems |
| Collection | Gather data to steal |
| Command and Control | Communicate with malware |
| Exfiltration | Steal data out |
| Impact | Destroy or disrupt |

*Tactics are ordered by typical attack flow.*`,
        questions: [
            ['How many Enterprise tactics are there?', '14', 'Fourteen', ['10', '12', '14', '20']],
            ['Which tactic involves stealing passwords?', 'Credential Access', 'Passwords', ['Execution', 'Credential Access', 'Discovery', 'Impact']],
            ['Which tactic is about maintaining access after initial compromise?', 'Persistence', 'Stay', ['Initial Access', 'Persistence', 'Exfiltration', 'Collection']]
        ]
    },
    313: {
        content: `# Techniques: The "How"

**Techniques** describe *how* adversaries achieve tactical goals.

## Example: Persistence Techniques
*   **T1547.001**: Registry Run Keys / Startup Folder.
*   **T1053**: Scheduled Task/Job.
*   **T1136**: Create Account.
*   **T1543**: Create or Modify System Service.

## Technique ID Format
*   **T#### **: Main technique (e.g., T1059 = Command and Scripting Interpreter).
*   **T####.###**: Sub-technique (e.g., T1059.001 = PowerShell).

## Procedures
Real-world examples of a technique in use.
*   *APT29 uses PowerShell (T1059.001) to execute payloads.*

## Mapping Your Detections
*   For each technique, ask: "Can I detect this?"
*   Build a coverage map.`,
        questions: [
            ['What is a "Sub-Technique"?', 'A more specific method under a main technique', 'Specific', ['A different framework', 'A more specific method under a main technique', 'A tool', 'A tactic']],
            ['T1059.001 refers to:', 'PowerShell execution', 'Script', ['Registry', 'PowerShell execution', 'DNS', 'HTTP']],
            ['What is a "Procedure" in ATT&CK?', 'Real-world example of technique usage', 'Example', ['A tactic', 'Real-world example of technique usage', 'A sub-technique', 'A detection rule']]
        ]
    },
    314: {
        content: `# Navigating the Matrix

**The ATT&CK Matrix** is a visual representation of tactics (columns) and techniques (rows).

## Using the Navigator
*   **MITRE ATT&CK Navigator**: Web-based tool to visualize coverage.
*   Color-code techniques by:
    *   **Detection coverage** (green = detected, red = gap).
    *   **Threat actor** (highlight techniques used by a specific APT).

## Key Resources
*   **attack.mitre.org**: The official website.
*   **Navigator**: Online visualization tool.
*   **STIX/TAXII**: Machine-readable ATT&CK data.

## Example Workflow
1.  Read a threat report about APT28.
2.  Open Navigator, search for APT28.
3.  See techniques they use (highlighted).
4.  Check if you detect those techniques.
5.  Prioritize gaps.`,
        questions: [
            ['What tool visualizes ATT&CK coverage?', 'ATT&CK Navigator', 'Tool', ['Wireshark', 'ATT&CK Navigator', 'Nmap', 'Burp Suite']],
            ['In the matrix, columns represent:', 'Tactics', 'Goals', ['Techniques', 'Tactics', 'Procedures', 'Tools']],
            ['What format provides machine-readable ATT&CK data?', 'STIX', 'Standard', ['PDF', 'STIX', 'CSV', 'DOCX']]
        ]
    },
    315: {
        content: `# Using ATT&CK for Defense

## Defensive Uses
1.  **Gap Analysis**: What techniques can we detect?
2.  **Prioritization**: Focus on techniques used by relevant threat actors.
3.  **Red Team Exercises**: Simulate specific techniques.
4.  **Vendor Evaluation**: "Does this EDR detect T1055 (Process Injection)?"
5.  **SOC Training**: Teach analysts about adversary behavior.

## Detection Engineering
*   Write detection rules mapped to techniques.
*   **Example**: Sysmon Event ID 11 (File Create) for T1105 (Ingress Tool Transfer).

## Threat-Informed Defense
*   Use threat intel to identify likely attackers.
*   Map their TTPs.
*   Build detections for those specific techniques.

## Continuous Improvement
*   As new techniques are published, assess coverage.
*   ATT&CK is updated regularly.`,
        questions: [
            ['How can ATT&CK help evaluate a security product?', 'Check if it detects specific techniques', 'Evaluation', ['By price', 'Check if it detects specific techniques', 'By color', 'By name']],
            ['What is "Gap Analysis" in ATT&CK context?', 'Identifying techniques you cannot detect', 'Missing', ['Finding bugs', 'Identifying techniques you cannot detect', 'Deleting logs', 'Writing reports']],
            ['Threat-Informed Defense means:', 'Building defenses based on likely threat actors', 'Focused', ['Random defenses', 'Building defenses based on likely threat actors', 'No defenses', 'Old defenses']]
        ]
    },
    316: {
        content: `# Final Quiz

Test your knowledge of the MITRE ATT&CK Framework.`,
        questions: [
            ['ATT&CK stands for:', 'Adversarial Tactics, Techniques, and Common Knowledge', 'Meaning', ['Attack Technical Team', 'Adversarial Tactics, Techniques, and Common Knowledge', 'Automated Threat Testing', 'None']],
            ['How many Enterprise tactics are there?', '14', 'Count', ['10', '12', '14', '16']],
            ['Techniques describe:', 'How adversaries achieve goals', 'Method', ['Why they attack', 'How adversaries achieve goals', 'Who attacks', 'When attacks happen']],
            ['T1059 refers to:', 'Command and Scripting Interpreter', 'Execution', ['Persistence', 'Command and Scripting Interpreter', 'Discovery', 'Exfiltration']],
            ['Which tool visualizes ATT&CK coverage?', 'Navigator', 'Visualization', ['Wireshark', 'Navigator', 'Nmap', 'Burp']],
            ['Gap Analysis identifies:', 'Techniques you cannot detect', 'Blind spots', ['Best techniques', 'Techniques you cannot detect', 'Fast techniques', 'Old techniques']]
        ]
    }
};

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