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

const overview = {
    id: 28,
    title: 'Digital Forensics Intro',
    description: 'Learn the fundamentals of collecting and analyzing digital evidence.',
    learning_path_id: 4
};

const tasks = [
    { id: 281, title: 'What is Digital Forensics?' },
    { id: 282, title: 'The Forensic Process' },
    { id: 283, title: 'Evidence Handling & Chain of Custody' },
    { id: 284, title: 'Disk Imaging & Acquisition' },
    { id: 285, title: 'File System Analysis (NTFS/ext4)' },
    { id: 286, title: 'Windows Artifacts' },
    { id: 287, title: 'Final Quiz' }
];

const lessons = {
    281: {
        content: `# What is Digital Forensics?

**Digital Forensics** is the science of identifying, preserving, analyzing, and presenting digital evidence.

## Use Cases
*   **Incident Response**: Determine how an attacker got in.
*   **Criminal Investigation**: Prove a crime occurred (child exploitation, fraud).
*   **Internal Investigation**: Employee misconduct, IP theft.
*   **Litigation Support**: eDiscovery for lawsuits.

## The Golden Rule
**Preserve the evidence.** Any change to the original data can make it inadmissible in court.

## Types of Forensics
*   **Disk Forensics**: Hard drives, SSDs, USB drives.
*   **Memory Forensics**: RAM analysis.
*   **Network Forensics**: Packet captures, logs.
*   **Mobile Forensics**: Phones, tablets.
*   **Cloud Forensics**: AWS, Azure, GCP artifacts.`,
        questions: [
            ['What is the "Golden Rule" of forensics?', 'Preserve the evidence', 'Do not alter', ['Delete everything', 'Preserve the evidence', 'Work fast', 'Guess the answer']],
            ['Which forensics type focuses on RAM?', 'Memory Forensics', 'Volatile', ['Disk', 'Memory Forensics', 'Network', 'Mobile']],
            ['Why is forensics used in lawsuits?', 'eDiscovery and litigation support', 'Legal', ['For fun', 'eDiscovery and litigation support', 'To delete evidence', 'To hack']]
        ]
    },
    282: {
        content: `# The Forensic Process

A structured methodology ensures evidence is admissible in court.

## The 4 Phases
1.  **Identification**: Locate potential sources of evidence.
2.  **Preservation**: Protect evidence from alteration (imaging).
3.  **Analysis**: Examine the evidence for relevant artifacts.
4.  **Presentation**: Report findings in a clear, understandable way.

## Legal Considerations
*   **Search Warrant**: Required in criminal cases.
*   **Consent**: Employee devices may require signed policy.
*   **Chain of Custody**: Document who touched the evidence and when.

## Tools of the Trade
*   **FTK Imager**: Free disk imaging tool.
*   **Autopsy**: Open-source forensic platform.
*   **EnCase**: Commercial forensic suite.
*   **Volatility**: Memory forensics framework.`,
        questions: [
            ['What is the first phase of the forensic process?', 'Identification', 'Find', ['Analysis', 'Identification', 'Presentation', 'Deletion']],
            ['Which tool is used for free disk imaging?', 'FTK Imager', 'Free', ['Wireshark', 'FTK Imager', 'Nmap', 'Burp Suite']],
            ['What document tracks who touched the evidence?', 'Chain of Custody', 'Log', ['Resume', 'Chain of Custody', 'Invoice', 'Email']]
        ]
    },
    283: {
        content: `# Evidence Handling & Chain of Custody

## Chain of Custody
A chronological record of:
*   Who collected the evidence.
*   When it was collected.
*   How it was stored.
*   Who had access.

**If broken, evidence may be thrown out in court.**

## Best Practices
1.  **Label everything**: Evidence bags with date, case number, signature.
2.  **Photograph the scene**: Before touching anything.
3.  **Use write blockers**: Prevent accidental modification.
4.  **Store securely**: Locked room, limited access.
5.  **Document transfers**: Every handoff is logged.

## Write Blockers
Hardware or software that allows *reading* a disk but *blocks* any writes.
*   **Hardware**: Tableau, CRU.
*   **Software**: Windows Registry modification (less reliable).`,
        questions: [
            ['What happens if Chain of Custody is broken?', 'Evidence may be inadmissible in court', 'Thrown out', ['Nothing', 'Evidence may be inadmissible in court', 'Faster trial', 'Automatic win']],
            ['What does a write blocker do?', 'Allows reading but prevents writing to evidence', 'Read-only', ['Speeds up the disk', 'Allows reading but prevents writing to evidence', 'Encrypts data', 'Deletes files']],
            ['What should you do before touching evidence?', 'Photograph the scene', 'Document', ['Delete logs', 'Photograph the scene', 'Guess', 'Nothing']]
        ]
    },
    284: {
        content: `# Disk Imaging & Acquisition

## Why Image?
You NEVER analyze the original disk. Always work on a **forensic copy**.

## Types of Acquisition
1.  **Physical Image**: Bit-for-bit copy of the entire disk (including deleted data).
2.  **Logical Image**: Only the files visible to the OS (faster, less complete).
3.  **Live Acquisition**: Imaging a running system (captures RAM too).

## Common Formats
*   **RAW (dd)**: Exact copy, no compression.
*   **E01 (EnCase)**: Compressed, includes metadata, hash verification.
*   **AFF4**: Advanced Forensic Format.

## Verification
After imaging, calculate a **hash (MD5/SHA256)** of both the source and the image.
*   If they match: Image is a perfect copy.
*   If they differ: Something went wrong.`,
        questions: [
            ['Why should you image a disk before analysis?', 'To preserve the original evidence', 'Protect', ['It is faster', 'To preserve the original evidence', 'To delete files', 'No reason']],
            ['Which acquisition type captures deleted data?', 'Physical Image', 'Complete', ['Logical', 'Physical Image', 'Live', 'None']],
            ['How do you verify a disk image is accurate?', 'Compare hashes of source and image', 'Hash match', ['Guess', 'Compare hashes of source and image', 'Look at it', 'Count files']]
        ]
    },
    285: {
        content: `# File System Analysis (NTFS/ext4)

## NTFS (Windows)
*   **MFT (Master File Table)**: Database of every file on the volume.
*   **$LogFile**: Transaction log (file creation, deletion).
*   **$UsnJrnl**: Change journal (tracks modifications).
*   **Alternate Data Streams (ADS)**: Hidden data attached to files.

## ext4 (Linux)
*   **Inodes**: Metadata about files (permissions, timestamps).
*   **Journal**: Records changes before committing.
*   **Deleted Files**: Inodes may still point to data blocks until overwritten.

## Timestamps (MACB)
*   **M**odified: Content changed.
*   **A**ccessed: File opened.
*   **C**hanged (MFT): Metadata changed.
*   **B**irth: File created.

*Attackers may "timestomp" to change these.*`,
        questions: [
            ['What is the MFT in NTFS?', 'Master File Table - database of all files', 'Index', ['Main Folder Tree', 'Master File Table - database of all files', 'Memory File Track', 'My First Table']],
            ['What can Alternate Data Streams (ADS) be used for?', 'Hiding data attached to files', 'Steganography', ['Speeding up reads', 'Hiding data attached to files', 'Compressing files', 'Encrypting']],
            ['What is "Timestomping"?', 'Modifying timestamps to hide activity', 'Anti-forensics', ['Creating timestamps', 'Modifying timestamps to hide activity', 'Deleting timestamps', 'Reading timestamps']]
        ]
    },
    286: {
        content: `# Windows Artifacts

## Registry Hives
*   **SAM**: User accounts and password hashes.
*   **SYSTEM**: System configuration, mounted devices.
*   **SOFTWARE**: Installed programs, autoruns.
*   **NTUSER.DAT**: User-specific settings (per user).

## Key Artifacts
| Artifact | Location | What it Shows |
|----------|----------|--------------|
| Recent Docs | NTUSER.DAT | Files recently opened |
| UserAssist | NTUSER.DAT | Programs run (ROT-13 encoded) |
| Prefetch | C:\\Windows\\Prefetch | Program execution history |
| Shimcache | SYSTEM | Files executed (even if deleted) |
| Amcache | C:\\Windows\\appcompat | Program installation |
| Event Logs | C:\\Windows\\System32\\winevt | Security, Application, System logs |

## Browser Artifacts
*   **History**: Sites visited.
*   **Downloads**: Files downloaded.
*   **Cookies**: Session data.`,
        questions: [
            ['Which registry hive contains user password hashes?', 'SAM', 'Security', ['SYSTEM', 'SAM', 'SOFTWARE', 'NTUSER']],
            ['What does Prefetch show?', 'Programs that have been executed', 'Execution', ['Network connections', 'Programs that have been executed', 'Passwords', 'Emails']],
            ['Where are Windows Event Logs stored?', 'C:\\Windows\\System32\\winevt', 'Logs path', ['Desktop', 'C:\\Windows\\System32\\winevt', 'Recycle Bin', 'Documents']]
        ]
    },
    287: {
        content: `# Final Quiz

Test your understanding of Digital Forensics basics.`,
        questions: [
            ['What is the golden rule of forensics?', 'Preserve the evidence', 'Protect', ['Analyze fast', 'Preserve the evidence', 'Delete duplicates', 'Guess']],
            ['Which tool is commonly used for memory forensics?', 'Volatility', 'RAM', ['FTK Imager', 'Volatility', 'Wireshark', 'Nmap']],
            ['What does a write blocker prevent?', 'Writing to evidence (preserve integrity)', 'Read-only', ['Reading', 'Writing to evidence (preserve integrity)', 'Deleting', 'Copying']],
            ['Which Windows artifact tracks program execution?', 'Prefetch', 'Execution', ['SAM', 'NTUSER', 'Prefetch', 'Cookies']],
            ['What file system feature allows hidden data in NTFS?', 'Alternate Data Streams (ADS)', 'Hidden', ['MFT', 'Alternate Data Streams (ADS)', 'Journal', 'Inodes']],
            ['What is the purpose of hashing a disk image?', 'Verify image integrity', 'Verification', ['Compress it', 'Verify image integrity', 'Encrypt it', 'Delete it']]
        ]
    }
};

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