const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../../.env') });
const db = require('../db');

async function updateLessonContent(taskId, title, content) {
    try {
        const check = await db.query('SELECT id FROM lesson_content WHERE task_id = ?', [taskId]);
        if (check.rows.length > 0) {
            await db.query('UPDATE lesson_content SET content = ? WHERE task_id = ?', [content, taskId]);
            console.log(`✅ Updated: [${taskId}] ${title}`);
        } else {
            await db.query('INSERT INTO lesson_content (task_id, content) VALUES (?, ?)', [taskId, content]);
            console.log(`✅ Inserted: [${taskId}] ${title}`);
        }
    } catch (error) {
        console.error(`❌ Error updating [${taskId}] ${title}:`, error.message);
    }
}

const lessons = [
    // --- NETWORKING CONTINUED ---
    {
        id: 25,
        title: "Subnetting Practice",
        content: `# 🧠 Subnetting Practice

Subnetting is a skill that requires muscle memory. Let's walk through common scenarios.

## The Magic Number Method
To find the subnet range:
1. Identifying the "interesting octet" (where the subnet mask changes from 255 to something else).
2. Subtract that mask value from **256**. The result is your "Magic Number" (Block Size).

### Example: /26
Subnet Mask: \`255.255.255.192\`
* Interesting Octet: 4th (192).
* Magic Number: \`256 - 192 = 64\`.
* Block Size: 64.
* Subnets:
    * 0 - 63
    * 64 - 127
    * 128 - 191
    * 192 - 255

## ✍️ Try it Yourself
**Scenario**: You have network \`192.168.10.0/24\`. You need to split it into 2 subnets.
* **New Mask**: \`/25\` (Borrow 1 bit).
* **Mask**: \`255.255.255.128\`.
* **Subnet A**: \`192.168.10.0\` to \`192.168.10.127\` (126 hosts).
* **Subnet B**: \`192.168.10.128\` to \`192.168.10.255\` (126 hosts).
`
    },
    {
        id: 27,
        title: "DHCP and ARP",
        content: `# DHCP & ARP: The Network Helpers

## DHCP (Dynamic Host Configuration Protocol) 🏷️
Imagine if you had to manually type in an IP address for every phone, laptop, and smart fridge in your house. That's a nightmare.
**DHCP** automates this.

### The DORA Process
How a device gets an IP:
1. **D**iscover: Client yells "Is there a DHCP server here?!" (Broadcast).
2. **O**ffer: Server says "Yes! You can have IP \`192.168.1.50\`".
3. **R**equest: Client says "I'll take it!".
4. **A**cknowledge: Server says "It's yours. Lease expires in 24 hours."

## ARP (Address Resolution Protocol) 📢
We know IP addresses (Layer 3), but switches only speak MAC addresses (Layer 2).
**ARP** bridges this gap. It asks "Who has IP \`192.168.1.1\`? Tell me your MAC address."

### ⚔️ ARP Poisoning
Since ARP has no verification, a hacker can reply "I am 192.168.1.1!".
The victim then sends all traffic to the hacker instead of the router. This is the classic **Man-in-the-Middle (MitM)** attack.
`
    },
    {
        id: 28,
        title: "Common Network Protocols",
        content: `# 📚 Common Network Protocols

A quick reference guide for essential protocols.

## File Transfer & Management
* **FTP (File Transfer Protocol)**: Port 20/21. Transfers files. Unencrypted.
* **SFTP / SCP (Secure)**: Port 22. Transfers files over SSH.
* **SMB (Server Message Block)**: Port 445. Windows file sharing. WannaCry ransomware exploited this (EternalBlue).

## Email 📧
* **SMTP (Simple Mail Transfer Protocol)**: Port 25. **Sending** email.
* **POP3 (Post Office Protocol)**: Port 110. **Receiving** email (Downloads and removes from server).
* **IMAP (Internet Message Access Protocol)**: Port 143. **Receiving** email (Syncs with server).

## Web 🌐
* **HTTP**: Port 80. Plain text web.
* **HTTPS**: Port 443. Encrypted web (TLS).

## Infrastructure
* **DNS**: Port 53. Domain names.
* **DHCP**: Port 67/68. IP assignment.
* **NTP (Network Time Protocol)**: Port 123. Syncs clocks. Critical for log analysis!
`
    },

    // --- SECURITY PRINCIPLES CONTINUED ---
    {
        id: 42,
        title: "Authorization vs. Authentication",
        content: `# 🚦 Authorization (AuthZ)

## The Difference
* **Authentication (AuthN)**: "Are you who you say you are?" (ID Card).
* **Authorization (AuthZ)**: "Are you allowed to go in here?" (Key Card Access Level).

You can be authenticated (logged in) but not authorized (access denied) to see the admin panel.

## Access Control Models
How do we decide who gets access?

### 1. DAC (Discretionary Access Control) 👤
The owner of the object decides.
* *Example*: Windows File Permissions. You create a file, you decide if "Bob" can read it.
* *Pros*: Flexible.
* *Cons*: Hard to manage in large orgs. Proliferation of access.

### 2. MAC (Mandatory Access Control) 👮
The system administrator decides based on clearance levels.
* *Example*: Military. "Top Secret" user can read "Top Secret" file.
* *Pros*: Very secure.
* *Cons*: Very rigid.

### 3. RBAC (Role-Based Access Control) 🎭
Access is based on your job function.
* *Example*: "Nurses" can view patient records. "Doctors" can edit them.
* *Pros*: Best for business. Easy to manage when people change jobs.

### 4. ABAC (Attribute-Based Access Control) 🧩
Access based on complex rules (Time, Location, Device).
* *Example*: "Managers can access HR files, but ONLY from the office Wi-Fi during business hours."
`
    },
    {
        id: 43,
        title: "Accounting (The 'A' in AAA)",
        content: `# 🧾 Accounting

In the **AAA** framework (Authentication, Authorization, Accounting), Accounting is often overlooked but critical for security.

## "Who did what?"
Accounting tracks user activity. It answers:
* **Who** accessed the system?
* **When** did they log in/out?
* **What** commands did they run?
* **How much** data did they transfer?

## Why is it important?
1. **Forensics**: If a breach happens, logs are the only evidence we have to reconstruct the crime scene.
2. **Billing**: In cloud (AWS/Azure), you pay for what you use.
3. **Compliance**: Laws (PCI-DSS, HIPAA) require strict audit trails.

## 📝 Logging Best Practices
* **Centralization**: Send all logs to a SIEM (Security Information and Event Management) system. Don't leave them on local machines where hackers can delete them.
* **Integrity**: Ensure logs cannot be modified (Write-Once storage).
* **Retention**: Keep logs for at least 3-12 months (depending on policy).
`
    },
    {
        id: 45,
        title: "Hashing vs. Encryption",
        content: `# 🥓 Hashing vs. Encryption

These two terms are often confused, but they serve different purposes.

## Encryption 🔐
* **Goal**: Confidentiality.
* **Reversible**: Yes! You can decrypt it if you have the key.
* **Use Case**: Sending a credit card number over the internet.

## Hashing #️⃣
* **Goal**: Integrity.
* **Reversible**: **NO!** It is a one-way function. You cannot "un-hash" data to get the original.
* **Use Case**: Storing passwords.
    * When you sign up, the site hashes your password \`Input -> SHA256 -> Hash\` and stores the hash.
    * When you login, it hashes your input again and compares the two hashes. The site never knows your actual password!

### Common Hash Functions
* **MD5**: Old, broken. Do not use.
* **SHA-1**: Old, broken. Do not use.
* **SHA-256**: Standard, secure.
* **Bcrypt**: Best for passwords (slow by design to stop brute-forcing).

## 🧂 Salting
If two users have the password "password123", they will have the same hash. To fix this, we add a random string (**Salt**) to each password before hashing.
`
    },
    {
        id: 46,
        title: "Defense in Depth",
        content: `# 🧅 Defense in Depth (Layered Security)

**Defense in Depth** is the strategy of using multiple layers of security to protect an asset. If one layer fails, another steps up.

## The Castle Analogy 🏰
1. **Moat**: (Firewall) First line of defense.
2. **Drawbridge**: (VPN/Authentication) Controlled entry.
3. **Guards**: (IDS/IPS) Monitoring for intruders.
4. **Vault**: (Encryption) Even if they get in, they can't read the treasure.

## Layers of IT Security
1. **Physical**: Fences, cameras, guards, locked server racks.
2. **Perimeter**: Firewalls, DDoS protection.
3. **Network**: VLANs, NAC (Network Access Control).
4. **Endpoint**: Antivirus, EDR (Endpoint Detection & Response).
5. **Application**: Input validation, WAF (Web App Firewall).
6. **Data**: Encryption, Backup.
7. **Human**: Security training, Phishing simulations.

> "There is no silver bullet in cybersecurity, only lead bullets... and lots of them."
`
    }
];

// Execute Updates
(async () => {
    console.log('🚀 Starting Phase 1 Content Update (Part 2)...');
    for (const lesson of lessons) {
        await updateLessonContent(lesson.id, lesson.title, lesson.content);
    }
    console.log('✨ Phase 1 Part 2 Complete.');
    process.exit(0);
})();
