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

const overview = {
    id: 34,
    title: 'Reporting & Documentation',
    description: 'Master the art of documenting investigations and writing reports.',
    learning_path_id: 4
};

const tasks = [
    { id: 341, title: 'Why Documentation Matters' },
    { id: 342, title: 'Incident Timelines' },
    { id: 343, title: 'Writing Effective Reports' },
    { id: 344, title: 'Executive Summaries' },
    { id: 345, title: 'Metrics and KPIs' },
    { id: 346, title: 'Final Quiz' }
];

const lessons = {
    341: {
        content: `# Why Documentation Matters

**If it isn't documented, it didn't happen.**

## Reasons to Document
1.  **Legal**: Evidence in court or regulatory audits.
2.  **Knowledge Transfer**: Others can understand what you did.
3.  **Lessons Learned**: Improve processes for next time.
4.  **Accountability**: Show what actions were taken and when.
5.  **Metrics**: Track performance over time.

## What to Document
*   **Investigations**: Every step, every finding.
*   **Incidents**: Timeline, impact, response actions.
*   **Decisions**: Why a certain action was taken.
*   **Evidence**: Chain of custody, hashes.

## Common Mistakes
*   ❌ "I'll remember it" (You won't).
*   ❌ Writing notes only at the end.
*   ❌ Using vague language ("some malware").
*   ✅ Document in real-time as you work.`,
        questions: [
            ['Why is real-time documentation important?', 'You will forget details later', 'Accurate', ['It is not', 'You will forget details later', 'It is slower', 'For fun']],
            ['Documentation is required for:', 'Legal evidence and audits', 'Compliance', ['Fun', 'Legal evidence and audits', 'Nothing', 'Vacation']],
            ['What should you avoid in documentation?', 'Vague language like "some malware"', 'Be specific', ['Details', 'Vague language like "some malware"', 'Timestamps', 'Evidence']]
        ]
    },
    342: {
        content: `# Incident Timelines

**A timeline is the backbone of any incident report.**

## What to Include
| Column | Description |
|--------|-------------|
| **Timestamp** | Exact time (UTC recommended) |
| **Source** | Where did this info come from? (SIEM, EDR, user) |
| **Event** | What happened? (Alert, Action, Discovery) |
| **Actor** | Who performed the action? (Attacker, Analyst, System) |
| **Evidence** | Link to log, screenshot, artifact |

## Example Timeline
| Timestamp (UTC) | Source | Event | Actor |
|-----------------|--------|-------|-------|
| 2024-01-15 10:00 | SIEM | Alert: Brute Force on SSH | System |
| 2024-01-15 10:15 | Analyst | Validated True Positive | John (SOC) |
| 2024-01-15 10:20 | EDR | Host isolated | System (Playbook) |
| 2024-01-15 10:30 | Analyst | Malware extracted for analysis | John (SOC) |

## Tips
*   Use **UTC** for consistency (avoid timezone confusion).
*   Be **specific** ("10:05:32" not "around 10am").
*   Link to **evidence** (log entries, screenshots).`,
        questions: [
            ['What timezone should timelines use?', 'UTC', 'Standard', ['Local', 'UTC', 'EST', 'Random']],
            ['What should every timeline entry include?', 'Timestamp, Source, Event, Actor', 'Complete', ['Just time', 'Timestamp, Source, Event, Actor', 'Just event', 'Nothing']],
            ['Why link to evidence in the timeline?', 'To support claims with proof', 'Verification', ['Decoration', 'To support claims with proof', 'Fun', 'Color']]
        ]
    },
    343: {
        content: `# Writing Effective Reports

**A report tells the story of the incident.**

## Report Structure
1.  **Executive Summary**: 1-2 paragraphs for leadership.
2.  **Scope**: What was investigated, what was not.
3.  **Timeline**: Chronological events.
4.  **Technical Findings**: IOCs, malware analysis, attack path.
5.  **Impact Assessment**: What was affected, data loss?
6.  **Recommendations**: How to prevent recurrence.
7.  **Appendix**: Raw logs, hashes, evidence.

## Writing Tips
*   **Know your audience**: Executives vs Technical team.
*   **Be concise**: Avoid jargon for non-technical readers.
*   **Use visuals**: Diagrams, charts, screenshots.
*   **Proofread**: Typos reduce credibility.

## Common Report Types
*   **Incident Report**: What happened, how we responded.
*   **Threat Assessment**: Risk from a specific threat actor.
*   **Vulnerability Report**: Findings from a scan/pentest.`,
        questions: [
            ['What comes first in an incident report?', 'Executive Summary', 'Top', ['Appendix', 'Executive Summary', 'Technical Findings', 'Timeline']],
            ['Who is the Executive Summary written for?', 'Leadership (non-technical)', 'C-Suite', ['Hackers', 'Leadership (non-technical)', 'Developers', 'Interns']],
            ['What should you include in an Appendix?', 'Raw logs, hashes, supporting evidence', 'Details', ['Summary', 'Raw logs, hashes, supporting evidence', 'Executive summary', 'Nothing']]
        ]
    },
    344: {
        content: `# Executive Summaries

**The most important part of any report for leadership.**

## What Executives Need to Know
*   **What happened?** (One sentence)
*   **What is the impact?** (Business terms: money, data, reputation)
*   **What did we do?** (Response actions)
*   **Are we safe now?** (Current status)
*   **What do we need?** (Resources, budget, decisions)

## Example Executive Summary
> On January 15, 2024, an attacker gained access to our network via a phishing email targeting the Finance department. The attacker exfiltrated customer payment data affecting approximately 10,000 records. Our IR team contained the threat within 4 hours by isolating affected systems. We have engaged legal counsel and are preparing customer notifications as required by GDPR. We recommend an immediate investment in email security and phishing training.

## Tips
*   **No jargon**: "Ransomware encrypted files" not "T1486 executed via PSExec."
*   **Quantify impact**: "$50,000 potential loss" not "significant impact."
*   **Be honest**: Don't hide bad news.`,
        questions: [
            ['What should an Executive Summary avoid?', 'Technical jargon', 'Simple', ['Details', 'Technical jargon', 'Impact', 'Recommendations']],
            ['How should impact be described?', 'In business terms (money, data, reputation)', 'Quantify', ['Technically', 'In business terms (money, data, reputation)', 'Vaguely', 'Not at all']],
            ['What question should the summary answer?', 'What happened and are we safe?', 'Status', ['Who is to blame?', 'What happened and are we safe?', 'What is for lunch?', 'Nothing']]
        ]
    },
    345: {
        content: `# Metrics and KPIs

**What gets measured gets improved.**

## Key SOC Metrics
| Metric | Description | Target |
|--------|-------------|--------|
| **MTTD** | Mean Time to Detect | Lower is better |
| **MTTR** | Mean Time to Respond | Lower is better |
| **MTTC** | Mean Time to Contain | Lower is better |
| **Alert Volume** | Total alerts per day/week | Baseline trend |
| **False Positive Rate** | % of alerts that are FP | Lower is better |
| **Escalation Rate** | % of alerts escalated to Tier 2 | Balanced |

## Why Metrics Matter
*   **Justify Budget**: Show improvements to leadership.
*   **Identify Gaps**: High FP rate = bad rules.
*   **Track Improvement**: Compare month over month.

## Dashboards
*   Use SIEM or BI tools (Grafana, Power BI).
*   Show trends, not just snapshots.
*   Make it visible (SOC wall displays).`,
        questions: [
            ['What does MTTD stand for?', 'Mean Time to Detect', 'Detection', ['Mean Time to Delete', 'Mean Time to Detect', 'Maximum Threat Time', 'None']],
            ['A high False Positive rate indicates:', 'Poor detection rules', 'Bad rules', ['Good security', 'Poor detection rules', 'Fast response', 'Nothing']],
            ['Why track metrics over time?', 'To identify trends and improvements', 'Progress', ['For fun', 'To identify trends and improvements', 'To delete data', 'No reason']]
        ]
    },
    346: {
        content: `# Final Quiz

Test your Reporting and Documentation skills.`,
        questions: [
            ['What timezone should incident timelines use?', 'UTC', 'Standard', ['Local', 'UTC', 'EST', 'Random']],
            ['Who is the Executive Summary written for?', 'Leadership', 'Audience', ['Hackers', 'Leadership', 'Developers', 'Public']],
            ['What does MTTR stand for?', 'Mean Time to Respond', 'Response', ['Mean Time to Read', 'Mean Time to Respond', 'Max Threat Time', 'None']],
            ['What should documentation avoid?', 'Vague language', 'Specific', ['Details', 'Vague language', 'Timestamps', 'Evidence']],
            ['What makes metrics valuable?', 'Tracking trends over time', 'Progress', ['One-time snapshots', 'Tracking trends over time', 'Colors', 'Nothing']],
            ['An Appendix should contain:', 'Raw evidence and supporting data', 'Details', ['Summary', 'Raw evidence and supporting data', 'Executive summary', 'Nothing']]
        ]
    }
};

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