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

const overview = {
    id: 21,
    title: 'Virtualization & Lab Setup',
    description: 'Build your own safe hacking laboratory using Virtual Machines.',
    learning_path_id: 2
};

const tasks = [
    { id: 211, title: 'Introduction to Virtualization' },
    { id: 212, title: 'Hypervisors: Type 1 vs Type 2' },
    { id: 213, title: 'Setting Up VirtualBox (Free)' },
    { id: 214, title: 'Setting Up VMware Workstation' },
    { id: 215, title: 'Creating Your First VM (Kali Linux)' },
    { id: 216, title: 'Network Modes: NAT, Bridged, Host-Only' },
    { id: 217, title: 'Snapshots & Clones (The Safety Net)' }
];

const lessons = {
    211: {
        content: `# Introduction to Virtualization

Before you hack, you need a safe place to practice. You cannot launch attacks against your real computer or random websites (that's illegal). You need a **Home Lab**.

## What is Virtualization?
Virtualization allows you to run multiple operating systems (Guests) on a single physical computer (Host) at the same time.

*   **Host**: Your physical laptop (Windows, Mac, or Linux).
*   **Guest**: The virtual computer running inside a window (e.g., Kali Linux, Windows 10 Target).

## Why do we need it?
1.  **Safety**: If you accidentally infect your VM with malware, your real computer remains safe. You just delete the VM.
2.  **Isolation**: You can create a private network where viruses cannot escape to the internet.
3.  **Efficiency**: You don't need 5 physical laptops. You can run 3 VMs on one laptop.`
    },
    212: {
        content: `# Hypervisors: Type 1 vs Type 2

The **Hypervisor** is the software that creates and runs virtual machines. It sits between the hardware and the virtual OS.

## Type 2 Hypervisor (Hosted)
This is what you will use for your home lab. It runs as an *application* on top of your existing OS.
*   **Pros**: Easy to install. You can keep using Windows/macOS as normal.
*   **Cons**: Slower performance (overhead from the Host OS).
*   **Examples**:
    *   **Oracle VirtualBox** (Free, Open Source).
    *   **VMware Workstation Pro** (Paid/Free for personal use).
    *   **VMware Fusion** (Mac).

## Type 1 Hypervisor (Bare Metal)
This replaces the Operating System entirely. You install it directly on the hardware. Used in enterprise data centers.
*   **Pros**: Extreme performance. Direct access to hardware variables.
*   **Cons**: You can't use the computer for anything else (no web browsing, gaming).
*   **Examples**:
    *   **VMware ESXi** (The Industry Standard).
    *   **Microsoft Hyper-V** (Server Core).
    *   **Proxmox VE** (Popular open-source choice for homelabs).
    *   **XenServer**.`
    },
    213: {
        content: `# Setting Up VirtualBox (Free)

Oracle VirtualBox is the most popular free hypervisor.

## Step 1: Download
*   Go to [virtualbox.org](https://www.virtualbox.org/).
*   Download the "Platform Package" for your OS (Windows hosts, OS X hosts).

## Step 2: Install
*   Run the installer. Accept the defaults.
*   **Critical**: If on Windows, you may need to disable "Hyper-V" in "Windows Features" if you get conflicts, although modern VirtualBox versions coexist better.
*   **Extension Pack**: Download and install the "VirtualBox Extension Pack" (same version). This adds USB 3.0 support and disk encryption.

## Step 3: BIOS/UEFI Check
If you get an error saying "VT-x is disabled", you must restart your computer, enter BIOS (F2 or Del), and enable **Intel VT-x** or **AMD-V** (Virtualization Technology).`
    },
    214: {
        content: `# Setting Up VMware Workstation

VMware is the industry standard. It often has better graphics performance (3D acceleration) than VirtualBox. Note: **VMware Workstation Pro is now free for personal use.**

## Step 1: Download
*   Go to the Broadcom/VMware support portal.
*   Download **VMware Workstation Pro**.

## Step 2: Install
*   Run the installer.
*   It handles network drivers more aggressively than VirtualBox.
*   On Mac: Use **VMware Fusion**. It is excellent for running Windows on Apple Silicon (M1/M2/M3).

## Comparison: VirtualBox vs VMware
*   **VirtualBox**: Free, Open Source, slightly slower graphics, best for vagrant/automation.
*   **VMware**: Faster graphics, smoother drag-and-drop, industry standard, proprietary.`
    },
    215: {
        content: `# Creating Your First VM (Kali Linux)

Let's build your attacking machine.

## Step 1: Get the ISO
*   Go to [kali.org/get-kali](https://www.kali.org/get-kali/).
*   Download the **Installer Image (ISO)** (recommended for learning installation) OR the **Virtual Machine** pre-built image (easiest).

## Step 2: Create VM (ISO Method)
1.  Open VirtualBox -> **New**.
2.  **Name**: "Kali Linux". **Type**: Linux. **Version**: Debian (64-bit).
3.  **RAM**: Give it at least 4GB (4096 MB).
4.  **CPU**: Give it at least 2 Cores.
5.  **Disk**: Create a virtual hard disk (VDI). Size: 50GB (Dynamically Allocated).

## Step 3: Attach ISO & Boot
1.  Go to **Settings** -> **Storage**.
2.  Click the "Empty" CD icon.
3.  Select your downloaded \`kali-linux-installer.iso\`.
4.  Click **Start**. Follow the Linux installer prompts.`
    },
    216: {
        content: `# Network Modes: NAT, Bridged, Host-Only

Understanding networking is critical for a lab. You don't want your malware VM talking to your family Printer.

## 1. NAT (Network Address Translation)
*   **Default**.
*   The VM sits behind the Host. It can browse the internet, but the internet cannot see it.
*   *Use Case*: Updating the VM, downloading tools.

## 2. Bridged Adapter
*   The VM connects *directly* to your home router. It gets an IP address from your home DHCP (e.g., 192.168.1.55).
*   **Danger**: The VM appears as a real device on your home network. Other devices (your TV, phone) can ping it.
*   *Use Case*: When you want the VM to act like a real server.

## 3. Host-Only Adapter
*   **The Safest**.
*   The VM creates a private network with *only* the Host. No internet access.
*   *Use Case*: Investigating malware. You don't want the malware "phoning home" to the C2 server. Also used for "VulnHub" target machines.`
    },
    217: {
        content: `# Snapshots & Clones (The Safety Net)

## Snapshots
A snapshot freezes the VM in time.
*   **Scenario**: You are about to run a dangerous exploit or update the system.
*   **Action**: Take a snapshot named "Before Update".
*   **Result**: If the update breaks everything, you click "Restore" and you are back in 5 seconds.
*   *Tip*: Always take a snapshot of a "Fresh Install" content so you never have to reinstall Linux again.

## Clones
*   **Linked Clone**: Creates a new VM that shares disk space with the parent. Fast to create, saves space.
*   **Full Clone**: A complete, independent copy. Uses more disk space but can be moved to another PC.`
    }
};

async function createModule21() {
    try {
        console.log('🚀 Creating Module 21: Virtualization...\n');

        // Create Module (Path 2)
        console.log(`Processing Module ${overview.id}: ${overview.title}`);
        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), learning_path_id = VALUES(learning_path_id)`, 
            [overview.id, overview.title, overview.description, 21, overview.learning_path_id]);

        // Create Tasks
        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), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }

        let totalLessons = 0;
        // Populate Lessons
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            // Clean
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]); // Ensure no questions remain

            // Insert Content
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 10]);
            
            // NO Questions inserted, as requested.
            totalLessons++;
        }

        console.log(`\n✅ Module 21 (Virtualization) Created! (${totalLessons} lessons, NO Questions)\n`);
        process.exit(0);

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

createModule21();
