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

async function createAllRemainingLessons() {
    try {
        console.log('Creating ALL remaining lessons for Modules 3-6...\n');

        // MODULE 3: Network Security Fundamentals (Tasks 14-18)
        console.log('=== MODULE 3: Network Security Fundamentals ===\n');

        // Task 14: TCP/IP Deep Dive
        const task14 = `# TCP/IP Protocol Suite

The TCP/IP model is the foundation of all internet communication. Understanding it is crucial for network security analysis.

## The Four Layers

### 1. Application Layer
- HTTP, HTTPS, FTP, SSH, DNS
- Where user applications interact with the network
- Most visible to end users

### 2. Transport Layer
**TCP (Transmission Control Protocol)**
- Reliable, connection-oriented
- Three-way handshake: SYN, SYN-ACK, ACK
- Used for: Web, Email, File Transfer

**UDP (User Datagram Protocol)**
- Fast, connectionless
- No reliability guarantees
- Used for: Streaming, Gaming, DNS

### 3. Internet Layer
- IP addressing and routing
- IPv4 and IPv6
- ICMP for diagnostics (ping, traceroute)

### 4. Network Access Layer
- Physical transmission
- Ethernet, Wi-Fi

## Security Implications

**TCP SYN Flood Attack:**
Attacker sends many SYN packets but never completes handshake, exhausting server resources.

**UDP Amplification:**
Small request generates large response, used in DDoS attacks.

## Common Ports to Know
- 20/21: FTP
- 22: SSH
- 23: Telnet (insecure!)
- 25: SMTP
- 53: DNS
- 80: HTTP
- 443: HTTPS
- 3389: RDP`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [14, task14, 'markdown', 8]);

        const task14Q = [
            [14, 'Reliable transport protocol?', 'TCP', 1, 'Connection-oriented', 0],
            [14, 'Fast connectionless protocol?', 'UDP', 2, 'No handshake', 0],
            [14, 'SSH port number?', '22', 3, 'Secure shell access', 0],
            [14, 'TCP handshake steps?', '3', 4, 'SYN, SYN-ACK, ACK', 0],
            [14, 'DNS port number?', '53', 5, 'Domain name lookups', 0]
        ];
        for (const q of task14Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 14: TCP/IP Deep Dive\n');

        // Task 15: Firewalls and Network Defense
        const task15 = `# Firewalls and Network Defense

Firewalls are the first line of defense in network security, controlling traffic flow based on security rules.

## Types of Firewalls

### Packet Filtering Firewall
- Examines packet headers
- Allows/blocks based on IP, port, protocol
- Fast but basic

### Stateful Firewall
- Tracks connection state
- Remembers legitimate sessions
- More secure than packet filtering

### Application Layer Firewall
- Inspects application data
- Can detect malicious payloads
- Example: Web Application Firewall (WAF)

## Firewall Rules

**Default Deny:**
Block everything, allow only necessary traffic.

**Default Allow:**
Allow everything, block known threats (less secure).

## Common Firewall Commands

**Linux (iptables):**
\`\`\`bash
sudo iptables -L                    # List rules
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -j DROP      # Default deny
\`\`\`

**Linux (ufw - easier):**
\`\`\`bash
sudo ufw status
sudo ufw allow 22/tcp
sudo ufw enable
\`\`\`

## Security Best Practices

✅ Use default deny policy
✅ Only open required ports
✅ Regular rule audits
✅ Log all blocked attempts
✅ Segment networks (DMZ)

❌ Don't allow all traffic
❌ Don't forget to update rules
❌ Don't expose unnecessary services`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [15, task15, 'markdown', 7]);

        const task15Q = [
            [15, 'First network defense?', 'Firewall', 1, 'Controls traffic flow', 0],
            [15, 'Best default policy?', 'Deny', 2, 'Block everything first', 0],
            [15, 'Linux firewall command?', 'iptables', 3, 'Packet filtering', 0],
            [15, 'Easy Ubuntu firewall?', 'ufw', 4, 'Uncomplicated Firewall', 0],
            [15, 'Application layer firewall?', 'WAF', 5, 'Web Application...', 0]
        ];
        for (const q of task15Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 15: Firewalls\n');

        // Task 16: Wireshark and Packet Analysis
        const task16 = `# Wireshark and Packet Analysis

Wireshark is the industry-standard tool for capturing and analyzing network traffic. Essential for SOC analysts.

## What is Wireshark?

A network protocol analyzer that lets you see what's happening on your network at a microscopic level.

## Basic Usage

### Capture Traffic
1. Select network interface
2. Click "Start" to begin capture
3. Let it run during suspicious activity
4. Click "Stop" when done

### Display Filters

**Filter by Protocol:**
\`\`\`
http
dns
tcp
udp
\`\`\`

**Filter by IP:**
\`\`\`
ip.addr == 192.168.1.100
ip.src == 10.0.0.5
ip.dst == 8.8.8.8
\`\`\`

**Filter by Port:**
\`\`\`
tcp.port == 80
udp.port == 53
\`\`\`

**Combine Filters:**
\`\`\`
ip.addr == 192.168.1.100 && tcp.port == 443
http.request.method == "POST"
\`\`\`

## Common Analysis Tasks

**Find HTTP Traffic:**
\`\`\`
http
\`\`\`

**Find Failed Connections:**
\`\`\`
tcp.flags.reset == 1
\`\`\`

**Follow TCP Stream:**
Right-click packet → Follow → TCP Stream

## Security Use Cases

✓ Detect malware communication
✓ Identify data exfiltration
✓ Analyze suspicious connections
✓ Troubleshoot network issues
✓ Investigate security incidents

## Pro Tips

- Use capture filters to reduce file size
- Save captures for later analysis
- Use Statistics → Conversations
- Check Protocol Hierarchy`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [16, task16, 'markdown', 9]);

        const task16Q = [
            [16, 'Packet analyzer tool?', 'Wireshark', 1, 'Network traffic viewer', 0],
            [16, 'Filter HTTP traffic?', 'http', 2, 'Display filter', 0],
            [16, 'Filter by IP?', 'ip.addr', 3, 'Address filter', 0],
            [16, 'View conversation?', 'Follow TCP Stream', 4, 'Right-click option', 0],
            [16, 'DNS filter?', 'dns', 5, 'Domain lookups', 0]
        ];
        for (const q of task16Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 16: Wireshark\n');

        // Task 17: VPNs and Encryption
        const task17 = `# VPNs and Encryption

Virtual Private Networks (VPNs) create secure tunnels over public networks, essential for remote work security.

## What is a VPN?

Creates encrypted tunnel between your device and VPN server, hiding your traffic from eavesdroppers.

## VPN Protocols

### OpenVPN
- Open source
- Very secure
- Widely supported
- Slower than WireGuard

### WireGuard
- Modern, fast
- Simple code base
- Growing adoption
- Excellent performance

### IPSec
- Built into most OSs
- Enterprise standard
- Complex setup

### PPTP (Avoid!)
- Old, insecure
- Should not be used
- Easy to crack

## How VPNs Protect You

✅ **Encryption:** Data is unreadable to interceptors
✅ **IP Masking:** Hides your real IP address
✅ **Bypass Geo-blocks:** Access regional content
✅ **Secure Public Wi-Fi:** Safe coffee shop browsing

## Common VPN Uses

**Personal:**
- Privacy protection
- Secure browsing
- Bypass censorship

**Enterprise:**
- Remote worker access
- Site-to-site connections
- Secure cloud access

## VPN Limitations

❌ Slows connection speed
❌ VPN provider can see traffic
❌ Not complete anonymity
❌ Some sites block VPNs

## Encryption Basics

**Symmetric:** Same key encrypts and decrypts (AES)
**Asymmetric:** Public/private key pairs (RSA)

**Modern Standard:** AES-256 encryption`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [17, task17, 'markdown', 8]);

        const task17Q = [
            [17, 'Secure network tunnel?', 'VPN', 1, 'Virtual Private Network', 0],
            [17, 'Modern fast protocol?', 'WireGuard', 2, 'New VPN standard', 0],
            [17, 'Avoid this protocol?', 'PPTP', 3, 'Old and insecure', 0],
            [17, 'Encryption standard?', 'AES-256', 4, 'Advanced Encryption Standard', 0],
            [17, 'Open source VPN?', 'OpenVPN', 5, 'Widely used', 0]
        ];
        for (const q of task17Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 17: VPNs\n');

        // Task 18: Network Security Tools
        const task18 = `# Network Security Tools

Essential tools every SOC analyst should know for network security assessment and incident response.

## Scanning Tools

### Nmap - Network Mapper
\`\`\`bash
nmap 192.168.1.0/24          # Scan subnet
nmap -sV 192.168.1.100       # Version detection
nmap -O 192.168.1.100        # OS detection
nmap -p 1-65535 target       # All ports
\`\`\`

### Netcat - Swiss Army Knife
\`\`\`bash
nc -l 1234                    # Listen on port
nc target 80                  # Connect to port
nc -zv target 20-100         # Port scan
\`\`\`

## Traffic Analysis

### tcpdump
\`\`\`bash
tcpdump -i eth0               # Capture on interface
tcpdump port 80               # Capture HTTP
tcpdump -w capture.pcap       # Save to file
\`\`\`

### Wireshark
GUI version of traffic analysis with deep protocol inspection.

## DNS Tools

### dig
\`\`\`bash
dig example.com               # DNS lookup
dig @8.8.8.8 example.com     # Specific DNS server
dig -x 8.8.8.8               # Reverse lookup
\`\`\`

### nslookup
\`\`\`bash
nslookup example.com
\`\`\`

## Security Auditing

### Nikto - Web Scanner
\`\`\`bash
nikto -h http://target.com
\`\`\`

### Burp Suite
Web application security testing platform.

## Monitoring Tools

### Snort - IDS/IPS
Intrusion detection and prevention system.

### Suricata
Modern IDS/IPS with multi-threading.

## Quick Reference

| Tool | Purpose |
|------|---------|
| Nmap | Port scanning |
| Wireshark | Packet analysis |
| tcpdump | CLI packet capture |
| Netcat | Network Swiss Army knife |
| Snort | Intrusion detection |`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
            [18, task18, 'markdown', 10]);

        const task18Q = [
            [18, 'Port scanning tool?', 'Nmap', 1, 'Network mapper', 0],
            [18, 'Network Swiss Army knife?', 'Netcat', 2, 'nc command', 0],
            [18, 'DNS lookup tool?', 'dig', 3, 'Domain information', 0],
            [18, 'CLI packet capture?', 'tcpdump', 4, 'Terminal sniffer', 0],
            [18, 'Intrusion detection system?', 'Snort', 5, 'IDS/IPS', 0]
        ];
        for (const q of task18Q) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }
        console.log('✓ Task 18: Network Tools\n');

        console.log('✅ Module 3 complete! (5 lessons)\n');
        console.log('===================\n');

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

createAllRemainingLessons();
