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

async function createSecurityPrinciplesLessons() {
    try {
        console.log('🚀 Creating Detailed Security Principles Lessons (Module 10)\n');

        // 1. Ensure Task 47 (Quiz) exists
        await db.query(`
            INSERT INTO tasks (id, module_id, title, is_active) 
            VALUES (47, 10, 'Quiz: Security Principles', 1) 
            ON DUPLICATE KEY UPDATE title='Quiz: Security Principles', is_active=1
        `);

        // Content Mapping
        const lessons = {
            40: {
                title: 'CIA Triad',
                content: `# The CIA Triad: The Heart of Security

The **CIA Triad** is the foundational model for information security. It represents the three pillars that every security professional must protect.

## 1. Confidentiality (Privacy)
**Goal**: Only authorized people should see the data.
*   **Examples**: Encryption, Passwords, Two-Factor Authentication (2FA).
*   **Attack**: Data Breach, Snooping, Wiretapping.

## 2. Integrity (Accuracy)
**Goal**: Data must not be changed, destroyed, or tampered with.
*   **Examples**: Hashing, Digital Signatures, Version Control.
*   **Attack**: Man-in-the-Middle (tampering), SOL Injection (modifying DB).

## 3. Availability (Uptime)
**Goal**: Systems and data must be accessible when needed.
*   **Examples**: Backups, Redundancy, Load Balancers.
*   **Attack**: DDoS (Distributed Denial of Service), Ransomware (encrypting files against user will).`,
                questions: [
                    ['What does the "C" in CIA stand for?', 'Confidentiality', 'Privacy', ['Control', 'Confidentiality', 'Certification', 'Compliance']],
                    ['Which concept ensures data is not altered?', 'Integrity', 'Accuracy', ['Availability', 'Integrity', 'Confidentiality', 'Authentication']],
                    ['A DDoS attack primarily targets which pillar?', 'Availability', 'Uptime', ['Integrity', 'Confidentiality', 'Availability', 'Authorization']]
                ]
            },
            41: {
                title: 'Authentication Methods',
                content: `# Authentication: Who are you?

**Authentication (AuthN)** is the process of verifying a user's identity.

## The Factors of Authentication
We prove identity using:

1.  **Something You Know**: Password, PIN, Answer to secret question. (Most common, least secure).
2.  **Something You Have**: Smart Card, Phone (SMS Code), Hardware Token (YubiKey).
3.  **Something You Are**: Biometrics (Fingerprint, FaceID, Retina Scan).
4.  **Something You Do**: Typing rhythm, gait analysis.
5.  **Somewhere You Are**: GPS location, IP address.

## Multi-Factor Authentication (MFA)
Using **two or more** different factors.
*   *Password + PIN* = **NOT** MFA (Both are "Know").
*   *Password + Fingerprint* = **MFA** (Know + Are).`,
                questions: [
                    ['Which is "Something You Are"?', 'Biometrics', 'Body part', ['Password', 'Smart Card', 'Biometrics', 'Location']],
                    ['Which fits "Something You Have"?', 'Smart Card', 'Physical token', ['PIN', 'Password', 'Smart Card', 'Typing Speed']],
                    ['Using a Password and a Fingerprint is an example of what?', 'MFA', 'Multi-Factor', ['Single Sign On', 'MFA', 'Authorization', 'Encryption']]
                ]
            },
            42: {
                title: 'Authorization',
                content: `# Authorization: What can you do?

**Authorization (AuthZ)** happens *after* Authentication. Once we know who you are, what are you allowed to access?

## Models of Access Control

### 1. Discretionary Access Control (DAC)
*   **Owner-based**. The data owner decides who gets access.
*   *Example*: Windows File Permissions (Right-click -> Properties -> Security).

### 2. Mandatory Access Control (MAC)
*   **Label-based**. The Operating System decides based on security labels.
*   *Example*: Military / Top Secret systems (SELinux). Users cannot change permissions.

### 3. Role-Based Access Control (RBAC)
*   **Job-based**. Access is assigned to a "Role" (e.g., "HR Manager"), and users are assigned to roles.
*   *Example*: Corporate environments.

### 4. Least Privilege Principle
*   Users should have the **minimum** access necessary to do their job. Nothing more.`,
                questions: [
                    ['Which comes first?', 'Authentication', 'Who are you?', ['Authorization', 'Authentication', 'Accounting', 'Auditing']],
                    ['Which model uses security labels (Top Secret)?', 'MAC', 'Mandatory', ['DAC', 'RBAC', 'MAC', 'ABAC']],
                    ['The principle of giving minimum necessary rights is called?', 'Least Privilege', 'Minimal', ['Zero Trust', 'Least Privilege', 'Defense in Depth', 'Separation of Duties']]
                ]
            },
            43: {
                title: 'Accounting',
                content: `# Accounting: What did you do?

**Accounting** (or Auditing) tracks user activity. It is the "Trail" in "Audit Trail".

## The AAA Framework
1.  **Authentication**: ID Verification.
2.  **Authorization**: Permission Check.
3.  **Accounting**: Logging & Tracking.

## Why Accounting?
*   **Non-Repudiation**: A user cannot deny an action because there is proof (logs).
*   **Forensics**: Investigating what happened after a hack.
*   **Compliance**: Regulations (GDPR, HIPAA, PCI-DSS) require logs.

## What do we log?
*   Login times (Success/Failure).
*   Files accessed or deleted.
*   Commands executed (e.g., \`sudo\`).
*   Configuration changes.`,
                questions: [
                    ['Which AAA component tracks user actions?', 'Accounting', 'Logs', ['Authentication', 'Authorization', 'Accounting', 'Access']],
                    ['Preventing a user from checking or denying an action is called?', 'Non-Repudiation', 'Undeniable', ['Integrity', 'Encryption', 'Non-Repudiation', 'Availability']],
                    ['What is a primary use of Accounting logs?', 'Forensics', 'Investigation', ['Speed', 'Encryption', 'Forensics', 'Routing']]
                ]
            },
            44: {
                title: 'Encryption Basics',
                content: `# Encryption: Locking the Data

**Encryption** transforms readable data (**Plaintext**) into unreadable scrambled data (**Ciphertext**) using a math formula and a **Key**.

## Symmetric Encryption (Private Key)
*   **Same Key** is used to Lock (Encrypt) and Unlock (Decrypt).
*   **Pros**: Fast, good for large data.
*   **Cons**: How do you share the key safely?
*   **Algorithms**: AES (Gold Standard), DES (Obsolete/Weak), 3DES.

## Asymmetric Encryption (Public Key)
*   **Two Keys**:
    *   **Public Key**: Encrypts data. Shared with everyone.
    *   **Private Key**: Decrypts data. Kept secret.
*   **Pros**: Safe key exchange.
*   **Cons**: Slow.
*   **Algorithms**: RSA, ECC (Elliptic Curve).

## Use Case: HTTPS
1.  **Asymmetric** handles the "Handshake" to safely share a key.
2.  **Symmetric** is used for the actual session (speed).`,
                questions: [
                    ['Which encryption uses the SAME key for locking and unlocking?', 'Symmetric', 'Single Key', ['Asymmetric', 'Symmetric', 'Hashing', 'Public Key']],
                    ['Which algorithm is the current gold standard for symmetric encryption?', 'AES', 'Advanced Encryption Standard', ['DES', 'AES', 'MD5', 'RSA']],
                    ['What is Plaintext?', 'Readable data', 'Unencrypted', ['Ciphertext', 'Hashed data', 'Readable data', 'Key']]
                ]
            },
            45: {
                title: 'Hashing vs Encryption',
                content: `# Hashing vs Encryption

Many beginners confuse these two. They are VERY different.

## Encryption
*   **Reversible**: You can decrypt ciphertext back to plaintext if you have the key.
*   **Purpose**: Confidentiality (Hiding secrets).
*   **Example**: Sending a credit card number.

## Hashing
*   **One-Way**: You **cannot** reverse a hash to get the original data. It is a mathematical fingerprint.
*   **Purpose**: Integrity (Verifying data hasn't changed).
*   **Example**: Storing Passwords.
    *   We don't save your password "123456".
    *   We save the hash: \`e10adc3949ba59abbe...\`
    *   When you login, we hash your input and compare fingerprints.

## Common Hashing Algorithms
*   **MD5**: Broken, do not use.
*   **SHA-1**: Broken.
*   **SHA-256**: Secure standard. (Used in Bitcoin).`,
                questions: [
                    ['Is hashing reversible?', 'No', 'One-way function', ['Yes', 'No', 'Only with a key', 'Only for admins']],
                    ['What is the primary goal of hashing?', 'Integrity', 'Fingerprinting', ['Confidentiality', 'Availability', 'Integrity', 'Speed']],
                    ['Which hashing algorithm is considered secure today?', 'SHA-256', 'Standard', ['MD5', 'SHA-1', 'SHA-256', 'ROT13']]
                ]
            },
            46: {
                title: 'Defense in Depth',
                content: `# Defense in Depth (DiD)

**Defense in Depth** (also known as the "Castle Approach" or "Onion Model") is the practice of layering defenses. If one fails, another catches the attack.

## The Layers
1.  **Physical**: Guards, Cameras, Fences.
2.  **Perimeter**: Firewalls, DMZ.
3.  **Network**: VLANs, IPS/IDS.
4.  **Endpoint**: Antivirus, EDR, Patching on laptops.
5.  **Application**: Input validation, Secure Coding.
6.  **Data**: Encryption, Hashing.
7.  **Human**: Awareness Training (Phishing tests).

## Why?
No single solution provides 100% security.
*   Firewall might miss malicious traffic, but...
*   Antivirus catches the file download.
*   If AV fails, Lack of Admin Rights stops installation.`,
                questions: [
                    ['What is another name for Defense in Depth?', 'Layered Security', 'Onion', ['Single Point of Failure', 'Layered Security', 'Zero Trust', 'Active Defense']],
                    ['Which layer involves educating users?', 'Human', 'Training', ['Physical', 'Network', 'Human', 'Application']],
                    ['Why use multiple layers?', 'Redundancy', 'If one fails', ['Cost savings', 'Redundancy', 'Simplicity', 'Speed']]
                ]
            },
            47: {
                title: 'Quiz: Security Principles',
                content: `# Final Module Quiz

Prove your mastery of Security Principles.
Topics:
*   CIA Triad (Confidentiality, Integrity, Availability)
*   AAA (AuthN, AuthZ, Accounting)
*   Encryption & Hashing
*   Defense in Depth

Good luck!`,
                questions: [
                    ['What fundamental triad models information security?', 'CIA', 'Confidentiality Integrity Availability', ['ABC', 'CIA', 'RGB', 'SSH']],
                    ['Which element of CIA ensures systems are up and running?', 'Availability', 'Uptime', ['Confidentiality', 'Integrity', 'Availability', 'Authentication']],
                    ['Fingerprints and Retina scans are examples of?', 'Biometrics', 'Something you are', ['Passwords', 'Tokens', 'Biometrics', 'Smart Cards']],
                    ['Identifying a user is called?', 'Authentication', 'AuthN', ['Authorization', 'Accounting', 'Authentication', 'Access']],
                    ['Determining what a user is allowed to do is?', 'Authorization', 'AuthZ', ['Authentication', 'Accounting', 'Authorization', 'Auditing']],
                    ['Which access control model uses "Top Secret" labels?', 'MAC', 'Mandatory', ['DAC', 'MAC', 'RBAC', 'Rule-Based']],
                    ['Which access control model relies on the data owner?', 'DAC', 'Discretionary', ['MAC', 'DAC', 'RBAC', 'ABAC']],
                    ['Tracking user activities in logs is known as?', 'Accounting', 'The 3rd A', ['Authentication', 'Authorization', 'Accounting', 'Analysis']],
                    ['Which type of encryption uses a Public and Private key?', 'Asymmetric', 'Two keys', ['Symmetric', 'Asymmetric', 'Hashing', 'Linear']],
                    ['Which type of encryption uses a single shared key?', 'Symmetric', 'Faster', ['Asymmetric', 'Symmetric', 'Hashing', 'Private']],
                    ['Which function is One-Way and non-reversible?', 'Hashing', 'Fingerprint', ['Encryption', 'Encoding', 'Hashing', 'Compression']],
                    ['Which is a secure hashing algorithm?', 'SHA-256', 'Modern', ['MD5', 'SHA-1', 'SHA-256', 'CRC32']],
                    ['What is the best defense against social engineering?', 'User Training', 'Human layer', ['Firewalls', 'Encryption', 'User Training', 'Biometrics']],
                    ['Layering multiple security controls is called?', 'Defense in Depth', 'Onion', ['Offense in Depth', 'Defense in Depth', 'Single Defense', 'Zero Security']],
                    ['What does Non-Repudiation provide?', 'Proof of origin', 'Cannot deny', ['Privacy', 'Proof of origin', 'Speed', 'Availability']],
                    ['Which helps protect Data Integrity?', 'Hashing', 'Check change', ['Encryption', 'Hashing', 'Backups', 'Firewalls']],
                    ['What does MFA stand for?', 'Multi-Factor Authentication', '2+ factors', ['Multi-Factor Authorization', 'Multi-Function Access', 'Multi-Factor Authentication', 'Main Factor Auth']],
                    ['Is a password "Something you have"?', 'No', 'Something you know', ['Yes', 'No', 'Depends', 'Sometimes']],
                    ['Which layer of Defense in Depth includes Firewalls?', 'Network', 'Perimeter', ['Physical', 'Network', 'Human', 'Data']],
                    ['Which is NOT a pillar of the CIA triad?', 'Authorization', 'Not C-I-A', ['Confidentiality', 'Integrity', 'Availability', 'Authorization']]
                ]
            }
        };

        let totalCreated = 0;
        
        // Iterate through the lesson keys (IDs)
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            console.log(`Processing Task ${taskId}: ${lesson.title}`);

            // Clean up existing content
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);

            // Insert Content
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 10]);

            // Insert Questions (Max 3 for normal lessons, 20 for Quiz)
            const maxQs = taskId === 47 ? lesson.questions.length : Math.min(lesson.questions.length, 3);
            
            for (let j = 0; j < maxQs; 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]);
            }
            totalCreated++;
        }

        console.log(`\n✅ Module 10 (Security Principles) detailed content created! (${totalCreated} lessons)\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createSecurityPrinciplesLessons();
