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

const overview = {
    id: 44,
    title: 'Compliance & Frameworks',
    description: 'Navigate security compliance: NIST, ISO, SOC 2, PCI-DSS, and HIPAA.',
    learning_path_id: 4
};

const tasks = [
    { id: 441, title: 'Security Frameworks Overview' },
    { id: 442, title: 'NIST Cybersecurity Framework' },
    { id: 443, title: 'ISO 27001 & 27002' },
    { id: 444, title: 'SOC 2 Compliance' },
    { id: 445, title: 'PCI-DSS & HIPAA' },
    { id: 446, title: 'Final Quiz' }
];

const lessons = {
    441: {
        content: `# Security Frameworks Overview

Frameworks provide structure; compliance proves it.

## Why Frameworks?
*   **Common Language**: Everyone speaks the same security language.
*   **Best Practices**: Distilled expertise from industry.
*   **Legal/Contractual**: Required for business (customers, regulators).
*   **Risk Management**: Systematic approach to identifying and reducing risk.

## Framework vs Compliance
| Term | Meaning |
|------|---------|
| **Framework** | Guidelines/best practices (voluntary) |
| **Compliance** | Meeting specific requirements (mandatory) |
| **Audit** | Verification that requirements are met |
| **Certification** | Formal attestation of compliance |

## Major Frameworks
| Framework | Focus |
|-----------|-------|
| NIST CSF | General cybersecurity |
| ISO 27001 | ISMS certification |
| SOC 2 | Service organization controls |
| CIS Controls | Prioritized security controls |
| COBIT | IT governance |

## Major Regulations
| Regulation | Industry |
|------------|----------|
| PCI-DSS | Payment cards |
| HIPAA | US Healthcare |
| GDPR | EU Data Privacy |
| SOX | US Financial (public companies) |`,
        questions: [
            ['What is the difference between a framework and compliance?', 'Framework is guidance; compliance is mandatory requirements', 'Difference', ['Same thing', 'Framework is guidance; compliance is mandatory requirements', 'Compliance is optional', 'Framework is mandatory']],
            ['Why do organizations adopt security frameworks?', 'Common language, best practices, risk management', 'Benefits', ['For fun', 'Common language, best practices, risk management', 'To slow things down', 'No reason']],
            ['What is an audit?', 'Verification that requirements are met', 'Check', ['Sales pitch', 'Verification that requirements are met', 'Training', 'Party']]
        ]
    },
    442: {
        content: `# NIST Cybersecurity Framework

The most widely adopted voluntary framework in the US.

## The 5 Core Functions
| Function | Focus | Examples |
|----------|-------|----------|
| **Identify** | Know your assets, risks | Asset inventory, risk assessment |
| **Protect** | Safeguards | Access control, encryption, training |
| **Detect** | Find incidents | SIEM, EDR, monitoring |
| **Respond** | Handle incidents | IR plan, communication |
| **Recover** | Resume operations | Backups, DR, lessons learned |

## Implementation Tiers
| Tier | Description |
|------|-------------|
| 1 - Partial | Risk mgmt is ad-hoc, reactive |
| 2 - Risk Informed | Some processes, not org-wide |
| 3 - Repeatable | Consistent, approved processes |
| 4 - Adaptive | Continuous improvement, lessons learned |

## Profiles
*   **Current Profile**: Where you are today.
*   **Target Profile**: Where you want to be.
*   **Gap Analysis**: What's needed to get there.

## NIST CSF 2.0 (2024)
*   Added **Govern** function.
*   Expanded supply chain risk.`,
        questions: [
            ['How many core functions are in NIST CSF?', '5 (Identify, Protect, Detect, Respond, Recover)', 'Five', ['3', '5 (Identify, Protect, Detect, Respond, Recover)', '7', '10']],
            ['What is a "Profile" in NIST CSF?', 'Current or target state of cybersecurity posture', 'State', ['A social media page', 'Current or target state of cybersecurity posture', 'A firewall rule', 'A user account']],
            ['Which tier represents continuous improvement?', 'Tier 4 - Adaptive', 'Best', ['Tier 1', 'Tier 2', 'Tier 3', 'Tier 4 - Adaptive']]
        ]
    },
    443: {
        content: `# ISO 27001 & 27002

International standard for Information Security Management Systems (ISMS).

## ISO 27001
*   **Certifiable**: Organizations get audited and certified.
*   **ISMS Focused**: Establish, implement, maintain, improve ISMS.
*   **Risk-Based**: Identify risks, select controls to mitigate.

## ISO 27001 Structure
1.  **Clauses 4-10**: Management system requirements.
    *   Context, Leadership, Planning, Support, Operation, Evaluation, Improvement.
2.  **Annex A**: Control objectives (93 controls in ISO 27001:2022).

## ISO 27002
*   Guidance on implementing the controls in Annex A.
*   More detailed than 27001.

## Control Categories (27002:2022)
| Category | Examples |
|----------|----------|
| Organizational | Policies, roles, responsibilities |
| People | Screening, training, awareness |
| Physical | Secure areas, equipment security |
| Technological | Access control, cryptography, network security |

## Certification Process
1.  **Gap Analysis**: Current state vs ISO requirements.
2.  **Implement Controls**: Fix gaps.
3.  **Internal Audit**: Self-assessment.
4.  **Stage 1 Audit**: Documentation review (certification body).
5.  **Stage 2 Audit**: On-site verification.
6.  **Certification**: Issued for 3 years (annual surveillance).`,
        questions: [
            ['What does ISMS stand for?', 'Information Security Management System', 'ISMS', ['Internal Security Monitoring System', 'Information Security Management System', 'Internet Security Module Standard', 'None']],
            ['How long is ISO 27001 certification valid?', '3 years with annual surveillance audits', 'Three', ['Forever', '3 years with annual surveillance audits', '1 year', 'Monthly']],
            ['What is the purpose of ISO 27002?', 'Guidance on implementing ISO 27001 controls', 'How-to', ['Certification', 'Guidance on implementing ISO 27001 controls', 'Auditing', 'Pricing']]
        ]
    },
    444: {
        content: `# SOC 2 Compliance

Trust Services Criteria for service organizations.

## What is SOC 2?
*   Developed by AICPA.
*   For service providers storing customer data.
*   Attests that controls are in place.

## Trust Services Criteria (TSC)
| Criteria | Focus |
|----------|-------|
| **Security** | Protection against unauthorized access (REQUIRED) |
| **Availability** | System is available as agreed |
| **Processing Integrity** | Data processed accurately |
| **Confidentiality** | Confidential data is protected |
| **Privacy** | Personal information handled properly |

## SOC 2 Report Types
| Type | Description |
|------|-------------|
| **Type I** | Design of controls at a point in time |
| **Type II** | Operating effectiveness over a period (6-12 months) |

## Common Controls
*   Access control (MFA, RBAC).
*   Encryption (in transit, at rest).
*   Logging and monitoring.
*   Change management.
*   Incident response.

## SOC 2 Process
1.  **Readiness Assessment**: Gap analysis.
2.  **Control Implementation**: Fill gaps.
3.  **Type I or II Audit**: By CPA firm.
4.  **Report**: Shared with customers under NDA.`,
        questions: [
            ['Which SOC 2 criterion is always required?', 'Security', 'Core', ['Availability', 'Privacy', 'Security', 'Integrity']],
            ['What is the difference between SOC 2 Type I and Type II?', 'Type I is point-in-time; Type II tests over a period', 'Duration', ['Same thing', 'Type I is point-in-time; Type II tests over a period', 'Type II is faster', 'Type I is better']],
            ['Who performs SOC 2 audits?', 'CPA firm (independent auditors)', 'Auditor', ['Internal team', 'CPA firm (independent auditors)', 'Customers', 'Anyone']]
        ]
    },
    445: {
        content: `# PCI-DSS & HIPAA

Industry-specific compliance requirements.

## PCI-DSS (Payment Card Industry Data Security Standard)
*   **Applies to**: Any organization handling cardholder data.
*   **Version**: PCI-DSS 4.0 (2022).
*   **Enforced by**: Card brands (Visa, Mastercard).

### 12 PCI-DSS Requirements
1.  Install and maintain a firewall.
2.  Change vendor-supplied defaults.
3.  Protect stored cardholder data.
4.  Encrypt transmission of cardholder data.
5.  Protect against malware.
6.  Develop secure systems.
7.  Restrict access (need-to-know).
8.  Identify and authenticate access.
9.  Restrict physical access.
10. Track and monitor access.
11. Test security systems regularly.
12. Maintain security policy.

## HIPAA (Health Insurance Portability and Accountability Act)
*   **Applies to**: US healthcare entities (covered entities, business associates).
*   **Protects**: PHI (Protected Health Information).

### HIPAA Key Rules
| Rule | Focus |
|------|-------|
| **Privacy Rule** | Who can access PHI |
| **Security Rule** | Technical safeguards for ePHI |
| **Breach Notification** | Report breaches within 60 days |`,
        questions: [
            ['How many requirements does PCI-DSS have?', '12', 'Twelve', ['5', '10', '12', '20']],
            ['What does HIPAA protect?', 'PHI (Protected Health Information)', 'Health', ['Credit cards', 'PHI (Protected Health Information)', 'IP addresses', 'Passwords']],
            ['What is the HIPAA Breach Notification Rule?', 'Report breaches within 60 days', 'Notify', ['Delete data', 'Report breaches within 60 days', 'Hide breach', 'Nothing']]
        ]
    },
    446: {
        content: `# Final Quiz

Test your Compliance & Frameworks knowledge.`,
        questions: [
            ['NIST CSF has how many core functions?', '5', 'Functions', ['3', '5', '7', '10']],
            ['ISO 27001 certification lasts:', '3 years', 'Duration', ['Forever', '1 year', '3 years', '5 years']],
            ['Which SOC 2 criterion is mandatory?', 'Security', 'Required', ['Privacy', 'Availability', 'Security', 'Integrity']],
            ['PCI-DSS has how many requirements?', '12', 'Count', ['5', '10', '12', '15']],
            ['HIPAA protects:', 'Protected Health Information (PHI)', 'Health', ['Credit cards', 'Protected Health Information (PHI)', 'Passwords', 'IP addresses']],
            ['SOC 2 Type II tests controls over:', 'A period of time (6-12 months)', 'Duration', ['One day', 'A period of time (6-12 months)', 'One hour', 'Never']]
        ]
    }
};

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