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

const overview = {
    id: 32,
    title: 'Cloud Security Basics',
    description: 'Understand security challenges and controls in cloud environments.',
    learning_path_id: 4
};

const tasks = [
    { id: 321, title: 'Cloud Service Models (IaaS/PaaS/SaaS)' },
    { id: 322, title: 'Shared Responsibility Model' },
    { id: 323, title: 'AWS Security Fundamentals' },
    { id: 324, title: 'Azure Security Fundamentals' },
    { id: 325, title: 'Cloud Misconfigurations' },
    { id: 326, title: 'Final Quiz' }
];

const lessons = {
    321: {
        content: `# Cloud Service Models (IaaS/PaaS/SaaS)

Understanding cloud models is critical for knowing *who* is responsible for *what*.

## IaaS (Infrastructure as a Service)
*   **You get**: Virtual machines, networking, storage.
*   **You manage**: OS, patching, applications.
*   **Provider manages**: Physical hardware, virtualization.
*   **Examples**: AWS EC2, Azure VMs, GCP Compute Engine.

## PaaS (Platform as a Service)
*   **You get**: Managed platform for running applications.
*   **You manage**: Application code, data.
*   **Provider manages**: OS, runtime, middleware.
*   **Examples**: AWS Elastic Beanstalk, Azure App Service, Heroku.

## SaaS (Software as a Service)
*   **You get**: Fully managed application.
*   **You manage**: Data, user access.
*   **Provider manages**: Everything else.
*   **Examples**: Office 365, Salesforce, Gmail.`,
        questions: [
            ['In IaaS, who is responsible for patching the OS?', 'The customer', 'You', ['The provider', 'The customer', 'Nobody', 'Microsoft']],
            ['Which model gives you just the application?', 'SaaS', 'Software', ['IaaS', 'PaaS', 'SaaS', 'None']],
            ['AWS EC2 is an example of:', 'IaaS', 'Infrastructure', ['PaaS', 'SaaS', 'IaaS', 'FaaS']]
        ]
    },
    322: {
        content: `# Shared Responsibility Model

**Security "OF" the cloud vs Security "IN" the cloud.**

## Provider Responsibilities (Security OF the cloud)
*   Physical data center security.
*   Hardware, networking infrastructure.
*   Hypervisor security.
*   Compliance certifications.

## Customer Responsibilities (Security IN the cloud)
*   Data classification and encryption.
*   Identity and Access Management (IAM).
*   Network controls (Security Groups, NACLs).
*   Application security.
*   Logging and monitoring.

## The Dividing Line Shifts
| Model | Customer Responsibility |
|-------|------------------------|
| IaaS | OS, Apps, Data, IAM, Network |
| PaaS | Apps, Data, IAM |
| SaaS | Data, IAM |

*More abstraction = Less responsibility (but less control).*`,
        questions: [
            ['Who secures the physical data center?', 'The cloud provider', 'Provider', ['Customer', 'The cloud provider', 'Government', 'Nobody']],
            ['IAM is whose responsibility?', 'The customer (always)', 'You', ['Provider', 'The customer (always)', 'Maybe both', 'Neither']],
            ['In SaaS, what does the customer manage?', 'Data and user access', 'Limited', ['Everything', 'Data and user access', 'Hardware', 'Nothing']]
        ]
    },
    323: {
        content: `# AWS Security Fundamentals

## Identity and Access Management (IAM)
*   **Users**: Human identities.
*   **Roles**: Assigned to services (e.g., EC2 can access S3).
*   **Policies**: JSON documents defining permissions.
*   **Principle of Least Privilege**: Give minimum required access.

## Key Security Services
| Service | Purpose |
|---------|---------|
| **CloudTrail** | Logs API calls (who did what) |
| **GuardDuty** | Threat detection (anomaly/ML) |
| **Security Hub** | Aggregates security findings |
| **Config** | Tracks resource configurations |
| **WAF** | Web Application Firewall |
| **KMS** | Key Management Service |

## S3 Bucket Security
*   **Block Public Access**: Should be ON by default.
*   **Bucket Policies**: Control who can access.
*   **Encryption**: Enable Server-Side Encryption (SSE).`,
        questions: [
            ['Which AWS service logs API calls?', 'CloudTrail', 'Audit', ['GuardDuty', 'CloudTrail', 'Config', 'WAF']],
            ['What should be blocked by default on S3 buckets?', 'Public Access', 'Privacy', ['Private Access', 'Public Access', 'All Access', 'Admin Access']],
            ['What does IAM stand for?', 'Identity and Access Management', 'Identity', ['Internet Access Manager', 'Identity and Access Management', 'Internal Admin Module', 'Instance Access Mode']]
        ]
    },
    324: {
        content: `# Azure Security Fundamentals

## Azure AD (Entra ID)
*   **Identity Provider**: Manages users, groups, applications.
*   **Conditional Access**: Enforce MFA, block risky sign-ins.
*   **Privileged Identity Management (PIM)**: Just-in-time admin access.

## Key Security Services
| Service | Purpose |
|---------|---------|
| **Microsoft Defender for Cloud** | CSPM + CWPP |
| **Azure Sentinel** | Cloud-native SIEM |
| **Azure Policy** | Enforce compliance |
| **Key Vault** | Secrets and key management |
| **Network Security Groups (NSG)** | Firewall rules |
| **Azure AD Logs** | Sign-in and audit logs |

## Common Misconfigurations
*   Storage Accounts with public blob access.
*   NSGs allowing 0.0.0.0/0 on SSH/RDP.
*   Guest users with excessive permissions.`,
        questions: [
            ['What is Azure Sentinel?', 'Cloud-native SIEM', 'SIEM', ['Firewall', 'Cloud-native SIEM', 'Antivirus', 'VPN']],
            ['PIM provides:', 'Just-in-time admin access', 'Temporary', ['Permanent access', 'Just-in-time admin access', 'Public access', 'No access']],
            ['Which service manages secrets in Azure?', 'Key Vault', 'Secrets', ['Blob Storage', 'Key Vault', 'Azure AD', 'Sentinel']]
        ]
    },
    325: {
        content: `# Cloud Misconfigurations

**Misconfigurations are the #1 cause of cloud breaches.**

## Common Mistakes
1.  **Public S3 Buckets**: Sensitive data exposed to the internet.
2.  **Overly Permissive IAM**: "*" actions on "*" resources.
3.  **Default Credentials**: Using default admin/admin.
4.  **Open Security Groups**: 0.0.0.0/0 to SSH (22) or RDP (3389).
5.  **Unencrypted Data**: Data at rest or in transit not encrypted.
6.  **Logging Disabled**: CloudTrail/Azure Activity Logs off.

## Real-World Breaches
*   **Capital One (2019)**: SSRF attack + misconfigured WAF + overly permissive IAM role.
*   **Twitch (2021)**: Server misconfiguration exposed 125GB of source code.

## Prevention
*   **CSPM (Cloud Security Posture Management)**: Continuously scan for misconfigs.
*   **Infrastructure as Code (IaC)**: Define secure configs in code (Terraform).
*   **Automated Remediation**: Auto-fix violations.`,
        questions: [
            ['What is the #1 cause of cloud breaches?', 'Misconfigurations', 'Config', ['Hackers', 'Misconfigurations', 'Malware', 'Phishing']],
            ['What does CSPM stand for?', 'Cloud Security Posture Management', 'Posture', ['Cloud Security Policy Manager', 'Cloud Security Posture Management', 'Cyber Security PM', 'Cloud System Protection Mode']],
            ['Open Security Groups allowing 0.0.0.0/0 SSH is:', 'A critical misconfiguration', 'Bad', ['Normal', 'A critical misconfiguration', 'Recommended', 'Fast']]
        ]
    },
    326: {
        content: `# Final Quiz

Test your Cloud Security knowledge.`,
        questions: [
            ['In IaaS, who patches the operating system?', 'The customer', 'You', ['Provider', 'The customer', 'AWS', 'Nobody']],
            ['The Shared Responsibility Model divides:', 'Security responsibilities between customer and provider', 'Division', ['Costs', 'Security responsibilities between customer and provider', 'Users', 'Regions']],
            ['Which AWS service detects threats using ML?', 'GuardDuty', 'ML', ['CloudTrail', 'GuardDuty', 'Config', 'WAF']],
            ['What is Azure Sentinel?', 'Cloud-native SIEM', 'SIEM', ['VPN', 'Firewall', 'Cloud-native SIEM', 'Storage']],
            ['Public S3 buckets are:', 'A major security risk', 'Bad', ['Recommended', 'A major security risk', 'Fast', 'Cheap']],
            ['CSPM helps find:', 'Cloud misconfigurations', 'Errors', ['Malware', 'Cloud misconfigurations', 'Users', 'Costs']]
        ]
    }
};

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