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

async function createProxyLessons() {
    try {
        console.log('🚀 Creating Web Proxies Lessons (Module 14)\n');

        // 1. Rename Module
        await db.query(`UPDATE modules SET title = 'Web Proxies Fundamentals', description = 'Understand how proxies work, how to intercept traffic, and the basics of Burp Suite.', estimated_hours = 5 WHERE id = 14`);

        // 2. Define Tasks
        const tasks = [
            { id: 72, title: 'What is a Proxy?' },
            { id: 73, title: 'Burp Suite Basics' },
            { id: 74, title: 'Intercepting Requests' },
            { id: 75, title: 'Repeater & Decoder' },
            { id: 76, title: 'Proxy Chaining & VPNs' }
        ];

        // Ensure tasks exist and are active
        for (const t of tasks) {
            await db.query(`INSERT INTO tasks (id, module_id, title, is_active, display_order) VALUES (?, 14, ?, 1, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), is_active=1`, [t.id, t.title, t.id - 71]);
        }

        // 3. Content Mapping
        const lessons = {
            72: {
                title: 'What is a Proxy?',
                content: `# Introduction to Proxies

In simple terms, a **Proxy** is a middleman between you (the client) and the internet (the server).

## 1. Forward Proxy
*   **What it does**: Acts on behalf of the client.
*   **Example**: You are at school, and the school proxy blocks Facebook. Every request goes through the proxy first.

## 2. Reverse Proxy
*   **What it does**: Acts on behalf of the server.
*   **Example**: Google uses reverse proxies to balance the load of millions of users. You talk to the proxy, the proxy talks to the massive server farm.

## 3. The "Man-in-the-Middle" (MitM)
In cybersecurity, we often use an **Intercepting Proxy**. This sits between your browser and the target website, allowing you to pause, view, and modify data before it is sent.`,
                questions: [
                    ['What describes a Forward Proxy?', 'Acts for the client', 'School/Work proxy', ['Acts for the server', 'Acts for the client', 'Is a VPN', 'Is a firewall']],
                    ['What is the main role of an Intercepting Proxy?', 'View/Modify traffic', 'MitM', ['Speed up internet', 'View/Modify traffic', 'Encrypt data', 'Host websites']],
                    ['What typically uses a Reverse Proxy?', 'High traffic servers', 'Load balancing', ['Home users', 'High traffic servers', 'Laptops', 'Printers']]
                ]
            },
            73: {
                title: 'Burp Suite Basics',
                content: `# Meet Burp Suite

**Burp Suite** is the industry-standard tool for web application security testing. It is basically a powerful Intercepting Proxy.

## Key Components
1.  **Proxy**: The core tool. It lets you see and stop HTTP requests.
2.  **Repeater**: Lets you send the same request over and over again, changing small details (like testing a password field).
3.  **Intruder**: Automated attacks (like brute-forcing passwords).
4.  **Decoder**: Decodes data formats (Base64, URL encoding).

## Concept
Your browser sends a request -> Burp captures it -> You modify it -> You send it to the server.`,
                questions: [
                    ['What is Burp Suite primarily used for?', 'Web Security Testing', 'Hacking apps', ['Network Scanning', 'Web Security Testing', 'Password Management', 'Virus Scanning']],
                    ['Which component allows modifying and re-sending individual requests?', 'Repeater', 'Repeat', ['Proxy', 'Scanner', 'Repeater', 'Intruder']],
                    ['Which component is used for automated attacks?', 'Intruder', 'Brute force', ['Repeater', 'Intruder', 'Decoder', 'Comparer']]
                ]
            },
            74: {
                title: 'Intercepting Requests',
                content: `# Interception Mode

The most famous feature of Burp Suite is **Intercept On**.

## How it works
1.  You turn "Intercept On" in Burp.
2.  You click "Login" on a website.
3.  **The browser hangs**. It's waiting.
4.  **Burp shows the request**. You see the username and password in plain text.
5.  You can change the username from "user" to "admin" before clicking "Forward".

## Why modify headers?
*   **User-Agent**: Pretend to be an iPhone.
*   **Cookies**: Steal a session or impersonate another user.
*   **Referer**: Change where you came from.`,
                questions: [
                    ['What happens when "Intercept is On"?', 'Requests hang/pause', 'Waiting for you', ['Requests go faster', 'Requests hang/pause', 'Browser closes', 'Server errors']],
                    ['Why would you modify the User-Agent header?', 'Pretend to be a specific device', 'Mobile testing', ['To hack wifi', 'Pretend to be a specific device', 'To clear cache', 'To speed up login']],
                    ['What allows you to send the paused request to the server?', 'Forward button', 'Action', ['Drop button', 'Forward button', 'Stop button', 'Delete button']]
                ]
            },
            75: {
                title: 'Repeater & Decoder',
                content: `# Repeater & Decoder

## 1. Repeater
Imagine you found a confusing error message on a login page.
*   Instead of refreshing the browser 100 times, you send the request to **Repeater**.
*   You change specific characters \`user=admin'\`, \`user=admin"\` and click "Send".
*   You see the server response immediately on the right side.

## 2. Decoder
Websites encode data to travel safely.
*   **URL Encoding**: \`Hello%20World\` (%20 is a space).
*   **Base64**: \`SGVsbG8=\` (Hello).
*   Burp Decoder turns this gibberish back into readable text so you can understand what is being sent.`,
                questions: [
                    ['Why use Repeater instead of the browser?', 'Faster iteration', 'Testing variations', ['Better graphics', 'Faster iteration', 'Browser is blocked', 'It is automatic']],
                    ['What does %20 represent in URL encoding?', 'Space', 'Whitespace', ['Tab', 'Enter', 'Space', 'Slash']],
                    ['What tool converts Base64 back to text?', 'Decoder', 'Decode', ['Encoder', 'Decoder', 'Translator', 'Compiler']]
                ]
            },
            76: {
                title: 'Proxy Chaining & VPNs',
                content: `# Proxy Chaining & Anonymity

Sometimes one proxy isn't enough, or you need to access a hidden network (like Tor).

## Proxy Chains
This is connecting multiple proxies in a line.
*   **You -> Proxy A -> Proxy B -> Proxy C -> Target**
*   If Proxy C checks who you are, they only see Proxy B. They don't see YOU.

## Proxies vs VPNs
*   **Proxy**: Usually handles web traffic (HTTP/S) for the browser.
*   **VPN**: Encrypts **ALL** traffic from your computer (Games, Spotify, Browser, Updates).
*   **Combo**: You can run Burp Suite (Proxy) *through* a VPN for security + analysis.`,
                questions: [
                    ['What happens in a proxy chain?', 'Traffic hops through multiple nodes', 'A->B->C', ['Traffic is blocked', 'Traffic hops through multiple nodes', 'Traffic is deleted', 'Traffic is faster']],
                    ['What is the main difference between Proxy and VPN?', 'VPN encrypts entire device traffic', 'Scope', ['Proxy is faster', 'VPN is free', 'VPN encrypts entire device traffic', 'Proxy is hardware']],
                    ['If you chain A->B->C, who does the Target see?', 'Proxy C', 'The last one', ['You', 'Proxy A', 'Proxy B', 'Proxy C']]
                ]
            }
        };

        let totalCreated = 0;
        
        // Iterate through the lesson keys (IDs)
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            console.log(`Processing Task ${taskId}: ${lesson.title}`);

            // Clean up existing content
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);

            // Insert Content
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 5]);

            // Insert Questions (3 max)
            for (let j = 0; j < Math.min(lesson.questions.length, 3); j++) {
                const q = lesson.questions[j];
                const options = q[3] ? JSON.stringify(q[3]) : null;
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, options, case_sensitive) VALUES (?, ?, ?, ?, ?, ?, ?)',
                    [taskId, q[0], q[1], j + 1, q[2], options, 0]);
            }
            totalCreated++;
        }

        console.log(`\n✅ Web Proxies Module (14) Created! (${totalCreated} lessons)\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createProxyLessons();
