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

async function createBatch2() {
    try {
        console.log('🚀 Batch 2: Security Principles + Command Line\n');

        let totalCreated = 0;

        // ===== SECURITY PRINCIPLES (Tasks 40-46) =====
        console.log('=== Security Principles ===\n');

        const secLessons = [
            {
                id: 40,
                title: 'CIA Triad',
                content: `# CIA Triad

The foundation of information security.

## Three Pillars

### Confidentiality
**Goal:** Keep information secret from unauthorized users

**Methods:**
- Encryption
- Access controls
- Authentication
- Data classification

**Threats:** Eavesdropping, data breaches, social engineering

### Integrity
**Goal:** Ensure data accuracy and prevent unauthorized modification

**Methods:**
- Hashing
- Digital signatures
- Version control
- Checksums

**Threats:** Malware, unauthorized changes, bit flipping

### Availability
**Goal:** Ensure systems and data are accessible when needed

**Methods:**
- Redundancy
- Backups
- DDoS protection
- Failover systems

**Threats:** DDoS, ransomware, hardware failure

## Balancing CIA
🎯 Security is about balance:
- Strong encryption (C) may slow access (A)
- High availability may reduce security (C)
- Integrity checks take time (A)

## Real-World Examples
- **Bank ATM:** High A+I, moderate C
- **Military Secrets:** High C+I, moderate A
- **Social Media:** High A, moderate C+I`,
                questions: [
                    ['CIA stands for?', 'Confidentiality Integrity Availability', 'Three pillars'],
                    ['Keep secrets pillar?', 'Confidentiality', 'Privacy'],
                    ['Data accuracy pillar?', 'Integrity', 'Prevent tampering'],
                    ['Uptime pillar?', 'Availability', 'System access'],
                    ['Integrity method?', 'Hashing', 'Verify unchanged']
                ]
            },
            {
                id: 41,
                title: 'Authentication Methods',
                content: `# Authentication Methods

Proving you are who you say you are.

## Authentication Factors

### Something You Know
- Passwords
- PINs
- Security questions

**Weakness:** Can be guessed, stolen, shared

### Something You Have
- Smart cards
- Security tokens
- Mobile device (SMS codes)
- Hardware keys (YubiKey)

**Weakness:** Can be lost, stolen

### Something You Are
- Fingerprint
- Facial recognition
- Iris scan
- Voice recognition

**Weakness:** Can't be changed if compromised

## Multi-Factor Authentication (MFA)
Combining 2+ factors = much stronger security

**Examples:**
- Password + SMS code
- Fingerprint + PIN
- Smart card + Password

## Common Methods

**Basic Auth:** Username + Password
**OAuth:** Token-based access
**SAML:** SSO for enterprises
**Kerberos:** Ticket-based (Active Directory)
**Biometrics:** Fingerprint, face

## Password Best Practices
✅ 12+ characters
✅ Use password manager
✅ Unique per service
✅ Enable MFA everywhere
❌ Don't reuse passwords
❌ Don't share passwords`,
                questions: [
                    ['MFA full name?', 'Multi-Factor Authentication', 'Multiple factors'],
                    ['Password factor type?', 'Something You Know', 'Knowledge-based'],
                    ['Fingerprint factor type?', 'Something You Are', 'Biometric'],
                    ['Token factor type?', 'Something You Have', 'Physical device'],
                    ['AD auth protocol?', 'Kerberos', 'Ticket-based']
                ]
            },
            {
                id: 42,
                title: 'Authorization',
                content: `# Authorization

Determining what authenticated users can access.

## Authentication vs Authorization
- **Authentication:** Who are you?
- **Authorization:** What can you do?

## Access Control Models

### Role-Based Access Control (RBAC)
Permissions based on job role

**Example:**
- Admins: Full access
- Developers: Code + deploy
- Users: Read only

### Attribute-Based Access Control (ABAC)
Permissions based on attributes

**Attributes:**
- User: department, clearance
- Resource: classification
- Environment: time, location

### Mandatory Access Control (MAC)
System enforces access (military/government)
- Top Secret
- Secret
- Confidential
- Unclassified

### Discretionary Access Control (DAC)
Owner controls access (most common)
- File permissions
- Sharing settings

## Principle of Least Privilege
Give minimum access needed for job function.

## Access Control Lists (ACL)
Define who can access what:
\`\`\`
File: report.pdf
- Alice: Read, Write
- Bob: Read
- Charlie: No access
\`\`\``,
                questions: [
                    ['Role-based control?', 'RBAC', 'Job function access'],
                    ['Attribute-based control?', 'ABAC', 'Context-based'],
                    ['Minimum access principle?', 'Least Privilege', 'Need-to-know'],
                    ['Access definition list?', 'ACL', 'Permission rules'],
                    ['Owner controls?', 'DAC', 'Discretionary']
                ]
            },
            {
                id: 43,
                title: 'Accounting',
                content: `# Accounting (Auditing)

Tracking who did what, when.

## Purpose
- Monitor activity
- Detect anomalies
- Forensic investigation
- Compliance

## What to Log

### User Actions
- Login/logout
- File access
- Configuration changes
- Admin commands

### System Events
- Service starts/stops
- Errors
- Network connections
- Resource usage

### Security Events
- Failed logins
- Privilege escalation
- Policy violations
- Malware detections

## Log Analysis
\`\`\`
Who: User alice
What: Deleted file report.xlsx
When: 2024-12-25 14:30:15
Where: Server FS01
Result: Success
\`\`\`

## SIEM Integration
Security Information and Event Management
- Collect logs centrally
- Correlate events
- Alert on suspicious patterns
- Long-term storage

## Compliance Requirements
- HIPAA: 6 years
- PCI-DSS: 1 year online, 3 years archived
- SOX: 7 years
- GDPR: Varies

## Log Protection
✅ Centralized storage
✅ Tamper-proof
✅ Encrypted
✅ Regular backups
❌ Don't store on local system only`,
                questions: [
                    ['Tracking activity?', 'Accounting', 'Auditing logs'],
                    ['Central log system?', 'SIEM', 'Event management'],
                    ['Login timestamp?', 'When', 'Time of event'],
                    ['PCI log retention?', '1 year', 'Online duration'],
                    ['Log storage best?', 'Centralized', 'Not local only']
                ]
            },
            {
                id: 44,
                title: 'Encryption Basics',
                content: `# Encryption Basics

Making data unreadable without the key.

## Symmetric Encryption
**Same key** encrypts and decrypts

**Algorithms:**
- AES (Advanced Encryption Standard) ⭐
- DES (obsolete)
- 3DES (legacy)
- ChaCha20

**Pros:** Fast, efficient
**Cons:** Key distribution problem

**Use:** Bulk data encryption

## Asymmetric Encryption
**Two keys:** Public and Private

**How it works:**
- Public key: Encrypts (share freely)
- Private key: Decrypts (keep secret)

**Algorithms:**
- RSA
- ECC (Elliptic Curve)
- Diffie-Hellman

**Use:** Secure key exchange, digital signatures

## Encryption Strength
- **AES-128:** Good
- **AES-256:** Excellent (military grade)

## Transport Encryption
- **TLS/SSL:** HTTPS, secure connections
- **VPN:** Tunnel everything
- **SSH:** Secure remote access

## At-Rest Encryption
- **Full Disk:** BitLocker, FileVault
- **Database:** Column/row encryption
- **Files:** GPG, 7-Zip with password

## Key Management
🔑 Keys are critical:
- Rotate regularly
- Store securely
- Never hardcode
- Use key management systems`,
                questions: [
                    ['Same key encryption?', 'Symmetric', 'One key'],
                    ['Two key encryption?', 'Asymmetric', 'Public/Private'],
                    ['Military grade AES?', 'AES-256', '256-bit'],
                    ['Secure web protocol?', 'TLS', 'Transport Layer Security'],
                    ['Best symmetric algorithm?', 'AES', 'Advanced Encryption Standard']
                ]
            },
            {
                id: 45,
                title: 'Hashing vs Encryption',
                content: `# Hashing vs Encryption

Two different cryptographic techniques.

## Hashing
**One-way function** - cannot be reversed

**Properties:**
- Fixed output length
- Deterministic (same input = same hash)
- Fast to compute
- Avalanche effect (small change = totally different hash)

**Algorithms:**
- **SHA-256** ⭐ (recommended)
- **SHA-1** (deprecated)
- **MD5** (broken, don't use)

**Uses:**
- Password storage
- File integrity verification
- Digital signatures
- Blockchain

**Example:**
\`\`\`
Input: "password123"
SHA-256: ef92b778b...dc56f (64 chars)
\`\`\`

## Encryption
**Two-way** function - can be decrypted

**Uses:**
- Protecting data in transit
- Storing sensitive data
- Secure communications

## Key Differences

| Feature | Hashing | Encryption |
|---------|---------|------------|
| Reversible | No | Yes |
| Key needed | No | Yes |
| Output size | Fixed | Variable |
| Purpose | Integrity | Confidentiality |

## Password Storage
❌ **Never store** passwords in plaintext
❌ **Never store** encrypted passwords
✅ **Always** hash passwords (+ salt)

**Salt:** Random data added before hashing
Prevents rainbow table attacks

\`\`\`
password + salt → hash → store
\`\`\``,
                questions: [
                    ['One-way function?', 'Hashing', 'Cannot reverse'],
                    ['Two-way function?', 'Encryption', 'Can decrypt'],
                    ['Best hash algorithm?', 'SHA-256', 'Secure Hash'],
                    ['Store passwords how?', 'Hashed', 'Plus salt'],
                    ['Rainbow table defense?', 'Salt', 'Random data']
                ]
            },
            {
                id: 46,
                title: 'Defense in Depth',
                content: `# Defense in Depth

Layered security approach - no single point of failure.

## Castle Analogy
1. Moat (Perimeter firewall)
2. Outer wall (Network segmentation)
3. Guard tower (IDS/IPS)
4. Inner wall (Host firewall)
5. Vault (Encryption)
6. Guards (Access control)

## Security Layers

### Perimeter
- Firewall
- VPN
- DMZ

### Network
- Network segmentation
- IDS/IPS
- Network monitoring

### Host
- Antivirus
- Host firewall
- Patch management

### Application
- Input validation
- Secure coding
- WAF (Web Application Firewall)

### Data
- Encryption
- DLP (Data Loss Prevention)
- Backups

### People
- Security training
- Awareness programs
- Policies

## Why Multiple Layers?

If one fails, others provide protection.

**Example Breach:**
1. Attacker bypasses firewall
2. IDS detects suspicious traffic
3. Host firewall blocks connection
4. Even if breached, data is encrypted
5. Backups available for recovery

## Security Controls

**Preventive:** Stop attacks (firewall, access control)
**Detective:** Identify attacks (IDS, logs)
**Corrective:** Fix damage (backups, patches)

## Best Practices
✅ Assume breach will happen
✅ Layer defenses
✅ Monitor everything
✅ Regular updates
✅ Test defenses`,
                questions: [
                    ['Layered security?', 'Defense in Depth', 'Multiple barriers'],
                    ['Detect attacks control?', 'Detective', 'IDS/logs'],
                    ['Stop attacks control?', 'Preventive', 'Before breach'],
                    ['Network intrusion system?', 'IDS', 'Intrusion Detection'],
                    ['Assume what happens?', 'Breach', 'Will occur mindset']
                ]
            }
        ];

        for (const lesson of secLessons) {
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [lesson.id, lesson.content, 'markdown', 8]);

            for (let i = 0; i < lesson.questions.length; i++) {
                const q = lesson.questions[i];
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)',
                    [lesson.id, q[0], q[1], i + 1, q[2], 0]);
            }
            totalCreated++;
            console.log(`✓ ${lesson.title}`);
        }

        console.log(`\n✅ Security Principles complete! (${secLessons.length} lessons)\n`);
        console.log(`Total in this batch: ${totalCreated}\n`);

        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createBatch2();
