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

async function updateLessonContent(taskId, title, content) {
    try {
        // Check if content exists
        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 = [
    // --- MODULE: INTRODUCTION TO CYBERSECURITY ---
    {
        id: 1,
        title: "What is Cybersecurity?",
        content: `# What is Cybersecurity?

## 🛡️ Defining Cybersecurity
Cybersecurity is the practice of protecting systems, networks, and programs from digital attacks. These cyberattacks are usually aimed at accessing, changing, or destroying sensitive information; extorting money from users; or interrupting normal business processes.

Implementing effective cybersecurity measures is particularly challenging today because there are more devices than people, and attackers are becoming more innovative.

### The Core Goals (CIA Triad)
Security professionals often refer to the **CIA Triad** as the foundation of security:
1. **Confidentiality**: Keeping data private. Only authorized people can see it.
2. **Integrity**: Ensuring data hasn't been tampered with. It is accurate and trustworthy.
3. **Availability**: Ensuring systems are up and running when needed.

---

## 🌍 Why is it Important?
In our connected world, everyone benefits from advanced cyber defense programs. At an individual level, a cybersecurity attack can result in identity theft, extortion attempts, and the loss of important data like family photos.

- **Critical Infrastructure**: Power plants, hospitals, and financial service companies are all potential targets.
- **Economic Impact**: Cybercrime costs the global economy trillions of dollars annually.
- **Privacy**: Protecting personal information is a fundamental right.

## 🚀 Key Domains
Cybersecurity is a vast field containing several disciplines:
* **Network Security**: Protecting the computer network from intruders.
* **Application Security**: Keeping software and devices free of threats.
* **Information Security**: Protecting the integrity and privacy of data in storage and in transit.
* **Operational Security**: The processes and decisions for handling and protecting data assets.
* **Disaster Recovery**: How an organization responds to a cyber-incident or any other event that causes the loss of operations or data.
`
    },
    {
        id: 2,
        title: "Understanding Threats and Vulnerabilities",
        content: `# Threats vs. Vulnerabilities vs. Risks

In cybersecurity, we often use three terms that are related but distinct. Understanding the difference is crucial for any analyst.

## ⚠️ The Equation
> **Risk = Threat × Vulnerability × Impact**

### 1. Threat 🦹
A **Threat** is anything that can exploit a vulnerability, intentionally or accidentally, and obtain, damage, or destroy an asset.
* **Examples**: Hackers, malware, natural disasters, disgruntled employees.

### 2. Vulnerability 🔓
A **Vulnerability** is a weakness or gap in a security program that can be exploited by a threat to gain unauthorized access to an asset.
* **Examples**: Unpatched software, weak passwords, unlocked server room doors, lack of input validation (SQL Injection).

### 3. Risk 📉
**Risk** is the potential for loss, damage, or destruction of an asset as a result of a threat exploiting a vulnerability.
* **Goal**: We cannot eliminate risk entirely, but we can **mitigate** (reduce) it to an acceptable level.

---

## Common Threat Actors
Who are we fighting against?
* **Script Kiddies**: Unskilled attackers who use tools created by others.
* **Hacktivists**: attackers motivated by political or social causes (e.g., Anonymous).
* **Cybercriminals**: Motivated by money (Ransomware gangs).
* **Nation States**: Government-sponsored hackers (Espionage, Cyberwarfare).
* **Insider Threats**: Employees/contractors who misuse their access.

## 🛡️ Mitigation Strategies
How do we fix vulnerabilities?
1. **Patch Management**: Keeping software up to date.
2. **Hardening**: Disabling unnecessary services and closing ports.
3. **Training**: Educating users to recognize phishing.
`
    },
    {
        id: 3,
        title: "Career Paths in Cybersecurity",
        content: `# 🎓 Career Paths in Cybersecurity

Cybersecurity is not just "hacking". It's a massive industry with diverse roles suited for different skills—from technical coding to psychology and management.

## 🔴 The Red Team (Offensive Security)
These professionals simulate attacks to find weaknesses.
* **Penetration Tester (Ethical Hacker)**: Authorized to hack systems to find bugs.
* **Red Team Operator**: Simulates full-scope adverserial attacks (physical, social engineering, network).
* **Exploit Developer**: Writes code to exploit specific vulnerabilities.

## 🔵 The Blue Team (Defensive Security)
The defenders who detect and stop attacks.
* **SOC Analyst (Security Operations Center)**: Monitors logs and alerts for suspicious activity (Tier 1, 2, 3).
* **Incident Responder**: The "firefighters" who jump in when a breach occurs.
* **Threat Hunter**: Proactively searches networks for hidden threats that evaded defenses.
* **Security Engineer**: Builds and maintains security tools (Firewalls, SIEM, IDS).

## 🟣 The Purple Team
A collaborative mindset where Red and Blue teams work together to improve overall security posture.

## 🛡️ GRC (Governance, Risk, and Compliance)
* **Security Auditor**: Checks if the company follows laws (GDPR, HIPAA, PCI-DSS).
* **CISO (Chief Information Security Officer)**: Executive leadership.

---

## 📈 Salary Expectations
Cybersecurity is one of the highest-paying fields in tech.
* **Entry Level (SOC Analyst I)**: $60k - $85k
* **Mid Level (Pen Tester, Engineer)**: $90k - $130k
* **Senior/Management**: $150k+

## 🚀 How to Start?
1. **Learn the Basics**: Networking (IPs, Ports) and Linux are non-negotiable.
2. **Get Certified**: CompTIA Security+, Network+, or Google Cybersecurity Certificate.
3. **Hands-on Practice**: Use platforms like **InfoSecLabs**, TryHackMe, or HackTheBox.
4. **Build a Portfolio**: Write blogs about what you learn.
`
    },
    {
        id: 5,
        title: "Setting Up Your Lab Environment",
        content: `# 🧪 Building Your Hacking Lab

You cannot learn cybersecurity just by reading. You need to **do**. A home lab allows you to practice attacks and defenses safely without breaking real laws.

## 📦 Virtualization
Instead of buying 5 computers, we use **Virtual Machines (VMs)**. A VM is a computer running inside your computer.

### Hypervisors
Software that runs VMs.
* **VirtualBox**: Free, open-source, works on Windows/Mac/Linux. (Recommended for beginners).
* **VMware Workstation Player**: Free for personal use, robust.

## 🛠️ The Essential VMs

### 1. The Attacker: Kali Linux 🐉
Kali is a Debian-based Linux distribution packed with 600+ pre-installed security tools (Nmap, Metasploit, Burp Suite, Wireshark).
* **Download**: [kali.org](https://www.kali.org/get-kali/)
* **Default Creds**: \`kali:kali\`

### 2. The Victim: Metasploitable 🎯
An intentionally vulnerable Linux machine. It has open ports and old software.
* **NEVER** expose this to the internet. Use "Host-Only" or "NAT Network" mode.

### 3. The Defender: Security Onion / Splunk 🧅
A Linux distro for threat hunting, network security monitoring, and log management.

---

## 🔒 Networking Modes
When setting up VirtualBox, understand these network types:
1. **NAT**: VM can access internet, but internet can't access VM. Good for downloading updates.
2. **Bridged**: VM appears as a separate device on your home Wi-Fi. (Risky for vulnerable machines).
3. **Internal Network / Host-Only**: VMs can talk to each other and host, but NO internet. **Safest for malware analysis.**

## ✅ Task
1. Download and install **VirtualBox**.
2. Download the **Kali Linux VirtualBox Image**.
3. Import it and boot it up.
4. Open a terminal and run \`sudo apt update && sudo apt upgrade\`.
`
    },

    // --- MODULE: NETWORKING ESSENTIALS ---
    {
        id: 22,
        title: "OSI Model Explained",
        content: `# 🌐 The OSI Model

The **Open Systems Interconnection (OSI)** model is a conceptual framework used to describe the functions of a networking system. It splits communication into **7 Layers**.

mnemonic: **"Please Do Not Throw Sausage Pizza Away"** (Physical -> Application)

## The 7 Layers

### Layer 7: Application 🖥️
* **What**: Interaction with the software application.
* **Protocols**: HTTP, HTTPS, FTP, DNS, SSH, SMTP.
* **Data Unit**: Data.
* **Attack Surface**: Web attacks, Phishing.

### Layer 6: Presentation 🎁
* **What**: Translation, encryption, and compression. formats data for the application layer.
* **Formats**: SSL/TLS, JPEG, ASCII.

### Layer 5: Session 🤝
* **What**: Establishes, manages, and terminates connections (sessions).
* **Example**: Logging into a bank website.

### Layer 4: Transport 🚚
* **What**: End-to-end communication and reliability.
* **Protocols**: **TCP** (Reliable, handshake) vs **UDP** (Fast, fire-and-forget).
* **Data Unit**: Segments.
* **Device**: Firewalls.

### Layer 3: Network 🛣️
* **What**: Routing data between different networks (IP Addressing).
* **Protocols**: IPv4, IPv6, ICMP.
* **Data Unit**: Packets.
* **Device**: **Router**.

### Layer 2: Data Link 🔗
* **What**: Transfer data between nodes on the *same* network (MAC Addressing).
* **Protocols**: Ethernet, ARP, Wi-Fi (802.11).
* **Data Unit**: Frames.
* **Device**: **Switch**.

### Layer 1: Physical 🔌
* **What**: Physical hardware and transmission of raw bits.
* **Examples**: Cables (Cat6, Fiber), Hubs.
* **Data Unit**: Bits (1s and 0s).

---

## Why does a Hacker care?
* **Layer 1/2**: Sniffing Wi-Fi, MAC Spoofing.
* **Layer 3**: IP Spoofing, Ping sweeps.
* **Layer 4**: Port Scanning (Nmap).
* **Layer 7**: SQL Injection, XSS, Buffer Overflows.
`
    },
    {
        id: 23,
        title: "TCP/IP Protocol Suite",
        content: `# TCP/IP: The Language of the Internet

While OSI is a theoretical model, **TCP/IP** is the practical suite of protocols used by the internet today. It condenses the OSI 7 layers into 4 layers.

## TCP vs UDP
The layer 4 (Transport) giants. You MUST know the difference.

### TCP (Transmission Control Protocol)
* **Connection-Oriented**: "Reliable".
* **3-Way Handshake**: 
    1. **SYN** (Client: "Can I verify connection?")
    2. **SYN-ACK** (Server: "Yes, I acknowledge.")
    3. **ACK** (Client: "Great, let's talk.")
* **Use Cases**: Web browsing (HTTP), Email, File Transfer. Accuracy is more important than speed.

### UDP (User Datagram Protocol)
* **Connectionless**: "Unreliable" or "Best Effort".
* **No Handshake**: Just sends packets. If they get lost, too bad.
* **Use Cases**: Video streaming, Gaming, VoIP. Speed is king.

---

## Common Ports 🚪
A port allows a computer to run multiple services on one IP.
* **21**: FTP (File Transfer) - *Unencrypted*
* **22**: SSH (Secure Shell) - *Encrypted Remote Access*
* **23**: Telnet - *Unencrypted Remote Access (Avoid!)*
* **53**: DNS (Domain Name System)
* **80**: HTTP (Web)
* **443**: HTTPS (Secure Web)
* **3389**: RDP (Remote Desktop)

### 🕵️‍♂️ Analyst Tip
If you see traffic on port **22**, it's likely an admin managing a server. If you see traffic on port **4444**, it might be a Metasploit shell!
`
    },
    {
        id: 24,
        title: "IP Addressing and Subnetting",
        content: `# 📍 IP Addressing

An **IP Address** is like a digital home address. It allows devices to locate each other.

## IPv4 Breakdown
An IPv4 address looks like: \`192.168.1.1\`
* It is **32 bits** long.
* Divided into 4 octets (0-255).

### Public vs. Private IPs
* **Public IP**: Used on the internet. Unique globally. Assigned by ISP.
* **Private IP**: Used inside a Local Area Network (LAN). Non-routable on internet.
    * Class A: \`10.0.0.0\` to \`10.255.255.255\`
    * Class B: \`172.16.0.0\` to \`172.31.255.255\`
    * Class C: \`192.168.0.0\` to \`192.168.255.255\`

> 💡 **Fun Fact**: The IP \`127.0.0.1\` is called "localhost". It always refers to your own computer. "There's no place like 127.0.0.1".

---

## ✂️ Subnetting
Subnetting is the practice of dividing a network into smaller, manageable pieces (subnets).

### CIDR Notation
You will often see IPs written as: \`192.168.1.0/24\`.
The \`/24\` is the **Subnet Mask**.
* It means the first 24 bits are the **Network ID** (Street name).
* The remaining 8 bits are for **Hosts** (House numbers).

**Common CIDRs:**
* \`/24\` (255.255.255.0) -> **254** usable hosts. (Standard home network)
* \`/16\` (255.255.0.0) -> **65,534** usable hosts.
* \`/8\` (255.0.0.0) -> **~16 million** hosts.
* \`/32\` -> **1** specific IP.

### Why Subnet?
1. **Performance**: Reduces broadcast traffic.
2. **Security**: We can isolate departments (e.g., HR shouldn't talk to Engineering devs).
`
    },
    {
        id: 26,
        title: "DNS Fundamentals",
        content: `# 📖 DNS: The Phonebook of the Internet

**DNS (Domain Name System)** translates human-readable domain names (like \`google.com\`) into computer-readable IP addresses (like \`142.250.190.46\`).

## How it Works
When you type \`www.example.com\`:
1. **Browser Cache**: Computer checks if it already knows the IP.
2. **Recursive Resolver**: Asks your ISP's DNS server.
3. **Root Server**: Directs to the \`.com\` TLD server.
4. **TLD Server**: Directs to the Authoritative Name Server for \`example.com\`.
5. **Authoritative Server**: Returns the actual IP.

---

## 📝 DNS Record Types
* **A Record**: Maps hostname to IPv4 (\`1.2.3.4\`).
* **AAAA Record**: Maps hostname to IPv6.
* **CNAME**: Alias. Maps one domain to another (e.g., \`m.site.com\` -> \`mobile.site.com\`).
* **MX Record**: Mail Exchange. Directs email traffic.
* **TXT Record**: Text notes. Used for verification (SPF, DKIM).

## ⚔️ DNS Attacks
* **DNS Spoofing / Cache Poisoning**: Tricking a DNS server into saving a fake IP address, redirecting users to a phishing site.
* **DNS Tunneling**: Sneaking data out of a network encoded in DNS queries (often used by C2 servers to bypass firewalls).
* **Domain Shadowing**: Creating subdomains on a hacked legitimate domain.
`
    },
    {
        id: 29,
        title: "Wireshark Introduction",
        content: `# 🦈 Wireshark Introduction

**Wireshark** is the world's most popular network protocol analyzer. It lets you capture and browse the traffic running on a computer network.

## What can it do?
* Capture live packet data.
* Inspect the contents of packets (Deep Packet Inspection).
* Filter traffic to find specific conversations.
* Reconstruct TCP streams (see the full text of an email or web page).

## 🕵️‍♂️ The Interface
1. **Packet List Pane**: Top view. Lists all packets with Time, Source, Destination, Protocol, Length.
2. **Packet Details Pane**: Middle view. Shows the protocols structure (OSI layers) of the selected packet.
3. **Packet Bytes Pane**: Bottom view. Raw Hex and ASCII dump.

---

## 🔍 Essential Filters
Wireshark captures EVERYTHING. You need filters to find the needle in the haystack.

| Filter | What it does |
| :--- | :--- |
| \`ip.addr == 192.168.1.5\` | Show traffic to OR from this IP |
| \`ip.src == 192.168.1.5\` | Show traffic FROM this IP only |
| \`http\` | Show only HTTP traffic |
| \`http.request.method == "POST"\` | Show form submissions (logins, uploads) |
| \`tcp.port == 443\` | Show HTTPS traffic |
| \`dns\` | Show DNS queries |

## 🚩 Follow TCP Stream
Right-click a packet -> **Follow** -> **TCP Stream**.
This reassembles the conversation. If using HTTP (not HTTPS), you can often see usernames and passwords in plain text!
`
    },

    // --- MODULE: SECURITY PRINCIPLES ---
    {
        id: 40,
        title: "CIA Triad",
        content: `# 📐 The CIA Triad

The **CIA Triad** is the holy trinity of information security. Every security control relates to one or more of these principles.

## 1. Confidentiality 🤫
**Only authorized users can access the data.**
* **Threats**: Snooping, Data breaches, Shoulder surfing.
* **Controls**: Encryption (AES), Access Control Lists (ACLs), MFA, 2FA.
* *Example*: Your bank balance should only be visible to you and the bank.

## 2. Integrity ✍️
**The data is accurate and hasn't been tampered with.**
* **Threats**: Man-in-the-Middle attacks, Bit rot, Unauthorized database modification.
* **Controls**: Hashing (SHA-256), Digital Signatures, Checksums, File Integrity Monitoring (FIM).
* *Example*: If you transfer $100, the system shouldn't change it to $1000.

## 3. Availability ⏱️
**The data/system is accessible when needed.**
* **Threats**: Denial of Service (DoS/DDoS), Ransomware, Power outage, Natural disaster.
* **Controls**: Redundancy (RAID), Backups, Load Balancers, Cloud failover.
* *Example*: Amazon.com must be online 24/7/365.

---

## ⚖️ The Balancing Act
Security is always a trade-off.
* **High Confidentiality/Integrity** often reduces **Availability** (e.g., disconnecting a server from the internet makes it very secure but unavailable).
* **Convenience vs. Security**: Complex passwords are secure (Confidentiality) but hard to remember, leading to lockouts (Availability issue).
`
    },
    {
        id: 41,
        title: "Authentication Methods",
        content: `# 🔑 Authentication Methods

**Authentication (AuthN)** is proving **who you are**.
(Not to be confused with Authorization, which is what you allowed to do).

## The Three Factors of Authentication
Robust security requires **Multi-Factor Authentication (MFA)**, which combines at least **two** different types:

### 1. Something You Know 🧠
* Passwords
* PINs
* Security Questions
* *Weakness*: Can be guessed, phished, or brute-forced.

### 2. Something You Have 💳
* Smartphone (SMS/OTP App)
* Smart Card / ID Badge
* YubiKey (Hardware Token)
* *Weakness*: Can be stolen or lost.

### 3. Something You Are 👁️
* Fingerprint
* Retina scan
* Face ID
* *Weakness*: Privacy concerns; once a biometric is stolen, it can't be changed.

---

## 🚫 Common Attacks
* **Brute Force**: Trying every combination of characters (a, b, c... aa, ab...).
* **Dictionary Attack**: Trying words from a list of common passwords (rockyou.txt).
* **Credential Stuffing**: Using leaked usernames/passwords from one site (e.g., LinkedIn breach) to login to another (e.g., Netflix), since people reuse passwords.
* **Phishing**: Tricking user into typing their password on a fake site.
`
    },
    {
        id: 44,
        title: "Encryption Basics",
        content: `# 🔐 Encryption Basics

Encryption is the process of encoding information so only authorized parties can access it.

## Symmetric Encryption (Shared Key) 🔑
* **Concept**: The **SAME** key is used to encrypt and decrypt.
* **Analogy**: A door key. If you lock the door, you (or anyone with a copy of the key) can unlock it.
* **Algorithms**: AES (Advanced Encryption Standard), DES (Obsolete), RC4.
* **Pros**: Very fast. Good for bulk data (hard drives, WiFi).
* **Cons**: Key distribution is hard. How do I send you the key securely without it getting stolen?

## Asymmetric Encryption (Public Key) 🔑🗝️
* **Concept**: Uses a **PAIR** of keys:
    1. **Public Key**: Shared with everyone. Used to **Encrypt**.
    2. **Private Key**: Kept secret. Used to **Decrypt**.
* **Analogy**: A mailbox. Anyone can put mail in (Public), but only the person with the mailbox key can take it out (Private).
* **Algorithms**: RSA, ECC (Elliptic Curve), Diffie-Hellman.
* **Pros**: Solves key exchange problem.
* **Cons**: Much slower than symmetric.

## HTTPS (TLS)
The secure web uses **Hybrid** encryption.
1. Uses **Asymmetric** (RSA) to securely exchange a session key.
2. Uses **Symmetric** (AES) with that session key to transfer the webpage data quickly.
`
    }
];

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