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

const overview = {
    id: 43,
    title: 'Zero Trust Architecture',
    description: 'Never trust, always verify: Implementing zero trust principles.',
    learning_path_id: 4
};

const tasks = [
    { id: 431, title: 'Zero Trust Principles' },
    { id: 432, title: 'Identity as the Perimeter' },
    { id: 433, title: 'Microsegmentation' },
    { id: 434, title: 'Continuous Verification' },
    { id: 435, title: 'Zero Trust Implementation' },
    { id: 436, title: 'Final Quiz' }
];

const lessons = {
    431: {
        content: `# Zero Trust Principles

**"Never trust, always verify."**

## The Problem with Perimeter Security
*   Traditional model: Castle and moat.
*   Once inside the network, you're trusted.
*   **Reality**: Attackers get inside (phishing, VPN compromise).

## Zero Trust Core Principles
1.  **Verify Explicitly**: Always authenticate and authorize based on all data points.
2.  **Least Privilege Access**: Grant minimum access needed, just-in-time.
3.  **Assume Breach**: Design as if attackers are already inside.

## Key Tenets
*   **All resources are accessed securely**: No implicit trust based on network location.
*   **Access is granted per-session**: Not "once authenticated, always trusted."
*   **Access is determined by policy**: Dynamic, based on identity, device, behavior.

## NIST SP 800-207
*   The definitive Zero Trust Architecture guide.
*   Defines ZTA concepts, deployment models, use cases.`,
        questions: [
            ['What is the Zero Trust motto?', 'Never trust, always verify', 'Motto', ['Trust everyone', 'Never trust, always verify', 'Trust but verify', 'Always trust']],
            ['What does "Assume Breach" mean?', 'Design security as if attackers are already inside', 'Mindset', ['Panic', 'Design security as if attackers are already inside', 'Give up', 'Trust more']],
            ['Which NIST document defines Zero Trust Architecture?', 'SP 800-207', 'Standard', ['SP 800-53', 'SP 800-207', 'SP 800-171', 'SP 800-61']]
        ]
    },
    432: {
        content: `# Identity as the Perimeter

Network location no longer defines trust. Identity does.

## Identity-Centric Security
*   **Who**: User identity (human or machine).
*   **What**: Device identity and health.
*   **Where**: Location context (still useful, not decisive).
*   **How**: Authentication method strength.

## Strong Authentication
*   **MFA Required**: Passwords alone are not enough.
*   **Phishing-Resistant MFA**: FIDO2/WebAuthn, hardware keys.
*   **Passwordless**: Biometrics + device attestation.

## Conditional Access
*   Grant access based on combined signals:
    *   User risk score.
    *   Device compliance.
    *   Location.
    *   Application sensitivity.

## Example Policy
\`\`\`
IF user = contractor
AND device = non-compliant
AND app = financial_system
THEN block access
\`\`\`

## Identity Providers (IdP)
*   Azure AD / Entra ID.
*   Okta.
*   Ping Identity.
*   Google Workspace.`,
        questions: [
            ['In Zero Trust, what replaces network location as the trust boundary?', 'Identity', 'Who', ['Firewall', 'Identity', 'IP address', 'VPN']],
            ['What is phishing-resistant MFA?', 'FIDO2/WebAuthn hardware keys', 'Strong', ['SMS codes', 'FIDO2/WebAuthn hardware keys', 'Email codes', 'Security questions']],
            ['Conditional Access decisions are based on:', 'User, device, location, and application risk signals', 'Signals', ['Random', 'User, device, location, and application risk signals', 'Time only', 'IP only']]
        ]
    },
    433: {
        content: `# Microsegmentation

Don't let attackers move freely once inside.

## Traditional vs Microsegmentation
| Traditional | Microsegmentation |
|-------------|-------------------|
| Large flat network | Segmented by workload |
| Perimeter firewall | East-West firewalls |
| IP-based rules | Identity/context-based rules |

## Implementation Approaches
*   **Network-Based**: VLANs, SDN, next-gen firewalls.
*   **Host-Based**: Endpoint firewalls, agent-based.
*   **Application-Based**: Service mesh (Istio), API gateways.

## Zero Trust Network Access (ZTNA)
*   Replace VPN with per-application access.
*   User authenticates → Access broker → Specific app (not full network).
*   Products: Zscaler Private Access, Cloudflare Access, Google BeyondCorp.

## Benefits
*   Lateral movement is blocked.
*   Breach containment.
*   Visibility into East-West traffic.

## Challenges
*   Complexity in large environments.
*   Legacy application compatibility.
*   Performance overhead.`,
        questions: [
            ['What does microsegmentation prevent?', 'Lateral movement after initial compromise', 'Contain', ['Authentication', 'Lateral movement after initial compromise', 'Logging', 'Faster network']],
            ['What does ZTNA replace?', 'Traditional VPN', 'VPN', ['Firewall', 'Traditional VPN', 'SIEM', 'EDR']],
            ['Microsegmentation uses what type of traffic rules?', 'Identity/context-based, not just IP', 'Context', ['IP only', 'Identity/context-based, not just IP', 'Random', 'None']]
        ]
    },
    434: {
        content: `# Continuous Verification

Trust is not one-time; it's continuous.

## Session Trust
*   **Traditional**: Authenticate once, trusted for the session.
*   **Zero Trust**: Continuously evaluate trust throughout the session.

## Signals for Continuous Monitoring
*   **User Behavior**: Unusual actions, anomalous patterns.
*   **Device Health**: Patch status, endpoint protection.
*   **Threat Intelligence**: Is this IP associated with attacks?
*   **Session Anomalies**: Login from new location, impossible travel.

## Response Actions
*   **Step-Up Authentication**: Require additional verification.
*   **Session Termination**: End access immediately.
*   **Access Downgrade**: Reduce permissions to read-only.
*   **Alert**: Notify SOC for investigation.

## Technologies
| Technology | Role |
|------------|------|
| UEBA | User behavior analytics |
| EDR | Endpoint detection and response |
| CASB | Cloud access security broker |
| IdP | Identity provider with risk scoring |

## Real-Time Policy Enforcement
*   Policy engine evaluates signals in real-time.
*   Access can be revoked mid-session.`,
        questions: [
            ['What is continuous verification?', 'Evaluating trust throughout the session, not just at login', 'Ongoing', ['One-time check', 'Evaluating trust throughout the session, not just at login', 'Weekly audit', 'Never check']],
            ['What is a step-up authentication?', 'Requiring additional verification when risk increases', 'More MFA', ['Login', 'Requiring additional verification when risk increases', 'Password reset', 'Logout']],
            ['UEBA provides:', 'User and entity behavior analytics', 'Behavior', ['Firewall rules', 'User and entity behavior analytics', 'Encryption', 'Backups']]
        ]
    },
    435: {
        content: `# Zero Trust Implementation

Practical steps to adopt Zero Trust.

## Maturity Model
| Level | Description |
|-------|-------------|
| **0** | Perimeter-only security |
| **1** | Basic MFA, some segmentation |
| **2** | Identity-centric, conditional access |
| **3** | Microsegmentation, continuous verification |
| **4** | Fully automated, AI-driven ZT |

## Implementation Roadmap
1.  **Identify**: Map users, devices, applications, data.
2.  **Protect**: Implement strong identity, MFA, encryption.
3.  **Detect**: Deploy monitoring, UEBA, EDR.
4.  **Respond**: Automate response, integrate with SOAR.
5.  **Iterate**: Continuously improve based on findings.

## Quick Wins
*   Enable MFA everywhere.
*   Implement conditional access.
*   Deploy EDR on all endpoints.
*   Segment critical systems.

## Common Mistakes
*   ❌ Trying to do everything at once.
*   ❌ Ignoring legacy systems.
*   ❌ Forgetting about non-human identities (service accounts, APIs).
*   ✅ Start with crown jewels (most critical assets).`,
        questions: [
            ['What is the first step in Zero Trust implementation?', 'Identify users, devices, applications, and data', 'Discovery', ['Deploy firewall', 'Identify users, devices, applications, and data', 'Buy tools', 'Hire staff']],
            ['What are "Quick Wins" for Zero Trust?', 'MFA everywhere, conditional access, EDR', 'Easy', ['Nothing', 'MFA everywhere, conditional access, EDR', 'Complete overhaul', 'Do nothing']],
            ['What should you protect first?', 'Crown jewels (most critical assets)', 'Priority', ['Everything equally', 'Crown jewels (most critical assets)', 'Nothing', 'Random']]
        ]
    },
    436: {
        content: `# Final Quiz

Test your Zero Trust Architecture knowledge.`,
        questions: [
            ['Zero Trust motto is:', 'Never trust, always verify', 'Motto', ['Always trust', 'Never trust, always verify', 'Trust everyone', 'Trust but verify']],
            ['In Zero Trust, what is the new perimeter?', 'Identity', 'Boundary', ['Firewall', 'Identity', 'VPN', 'Router']],
            ['ZTNA replaces:', 'Traditional VPN', 'Access', ['SIEM', 'Traditional VPN', 'EDR', 'Antivirus']],
            ['Microsegmentation prevents:', 'Lateral movement', 'Contain', ['Authentication', 'Lateral movement', 'Logging', 'Backup']],
            ['Continuous verification means:', 'Trust is evaluated throughout the session', 'Ongoing', ['One check', 'Trust is evaluated throughout the session', 'Never check', 'Weekly']],
            ['First step in ZT implementation:', 'Identify users, devices, apps, data', 'Discovery', ['Buy tools', 'Identify users, devices, apps, data', 'Hire', 'Nothing']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 43: Zero Trust Architecture...\n');
        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)`, 
            [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', 20]);
            for (let j = 0; j < lesson.questions.length; j++) {
                const q = lesson.questions[j];
                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], JSON.stringify(q[3]), 0]);
            }
        }
        console.log(`✅ Module 43 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
