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

// This script creates lessons in large batches to maximize coverage
async function createMassLessons() {
    try {
        console.log('🚀 Mass Lesson Creation - Path 1 Expansion\n');

        let totalCreated = 0;

        // ===== WINDOWS FUNDAMENTALS (Tasks 32-39) =====
        console.log('=== Windows Fundamentals ===\n');

        const winLessons = [
            {
                id: 32,
                title: 'Windows File System',
                content: `# Windows File System

## Drive Structure
- **C:** - System drive  
- **D:, E:** - Additional/external drives

## Key Directories
- **C:\\Windows** - OS files, System32
- **C:\\Program Files** - 64-bit apps
- **C:\\Program Files (x86)** - 32-bit apps  
- **C:\\Users** - User profiles
- **C:\\ProgramData** - Shared app data (hidden)

## File Systems
**NTFS** - Modern, secure, permissions
**FAT32** - Simple, 4GB file limit
**exFAT** - Large files, portable drives

## Security Paths
- Logs: C:\\Windows\\System32\\winevt\\Logs
- Startup: C:\\Users\\[User]\\AppData\\...\\Startup
- Temp: C:\\Windows\\Temp

🚨 Attackers hide in: Temp, Startup, AppData, System32`,
                questions: [
                    ['What is the standard system drive letter?', 'C:', 'Primary Windows drive', ['A:', 'B:', 'C:', 'D:']],
                    ['Which file system is modern and supports permissions?', 'NTFS', 'Permissions supported', ['FAT32', 'NTFS', 'exFAT', 'HFS+']],
                    ['What is the max file size for FAT32?', '4 GB', 'Size limit', ['2 GB', '4 GB', '8 GB', 'Unlimited']],
                    ['Which directory stores shared application data?', 'ProgramData', 'Hidden folder in C:\\', ['Program Files', 'Users', 'ProgramData', 'Windows']],
                    ['Where are 64-bit applications typically installed?', 'Program Files', 'Not (x86)', ['Program Files (x86)', 'Program Files', 'Windows', 'AppData']]
                ]
            },
            {
                id: 33,
                title: 'User Account Control',
                content: `# User Account Control (UAC)

## Purpose
Prevents unauthorized system changes by requiring permission prompts.

## UAC Prompts
- **Blue Shield** - Trusted (signed)
- **Yellow Shield** - Unverified  
- **Red Shield** - Blocked

## Levels
1. Always Notify (most secure)
2. Notify (default)
3. Notify - Dim Desktop
4. Never Notify (unsafe!)

## Best Practices
✅ Keep UAC enabled
✅ Only approve prompts YOU initiated
✅ Verify publisher
✅ Use standard accounts daily
❌ Don't disable UAC`,
                questions: [
                    ['What does UAC stand for?', 'User Account Control', 'Permission system', ['User Access Control', 'User Account Control', 'Unified Access Center', 'Universal App Control']],
                    ['Which color shield indicates a trusted app?', 'Blue', 'Signed application', ['Red', 'Yellow', 'Blue', 'Green']],
                    ['Which UAC level is the most secure?', 'Always Notify', 'Maximum protection', ['Always Notify', 'Notify me only when apps try to make changes', 'Notify me (do not dim my desktop)', 'Never Notify']],
                    ['What account type should be used for daily tasks?', 'Standard', 'Not admin', ['Administrator', 'Standard', 'Guest', 'System']],
                    ['Is it safe to disable UAC?', 'No', 'Security risk', ['Yes', 'No', 'Only on weekends', 'Only for admins']]
                ]
            },
            {
                id: 34,
                title: 'Windows Registry',
                content: `# Windows Registry

## What is Registry?
Hierarchical database storing Windows and application settings.

## Registry Hives
- **HKEY_LOCAL_MACHINE (HKLM)** - System settings
- **HKEY_CURRENT_USER (HKCU)** - User settings
- **HKEY_CLASSES_ROOT** - File associations
- **HKEY_USERS** - All user profiles

## Data Types
- **REG_SZ** - String
- **REG_DWORD** - 32-bit number
- **REG_BINARY** - Binary data

## Registry Tools
- regedit.exe - Registry Editor
- reg.exe - Command line tool

## Security
🚨 Malware often modifies:
- Run keys (auto-start)
- Services
- File associations

## Important Keys
\`\`\`
HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run
HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run
\`\`\``,
                questions: [
                    ['Which hive stores system-wide settings?', 'HKLM', 'LOCAL_MACHINE', ['HKCU', 'HKLM', 'HKU', 'HKCR']],
                    ['What is the GUI tool for editing the registry?', 'regedit', 'Graphical editor', ['cmd', 'regedit', 'taskmgr', 'msconfig']],
                    ['Which data type is used for text strings?', 'REG_SZ', 'String Value', ['REG_DWORD', 'REG_BINARY', 'REG_SZ', 'REG_MULTI_SZ']],
                    ['Which Reg Key is commonly checked for persistence?', 'Run', 'Auto-start programs', ['MountPoints', 'Run', 'WinLogon', 'Services']],
                    ['Which hive stores settings for the currently logged-in user?', 'HKCU', 'CURRENT_USER', ['HKLM', 'HKCU', 'HKCR', 'HKCC']]
                ]
            },
            {
                id: 35,
                title: 'Active Directory Intro',
                content: `# Active Directory Introduction

## What is Active Directory (AD)?
Microsoft's directory service for managing users, computers, and resources in a network.

## Core Concepts

### Domain
- Logical group of network objects
- Example: company.com

### Domain Controller (DC)
- Server running AD
- Authenticates users
- Stores AD database

### Organizational Units (OUs)
- Containers for organizing objects
- Can apply Group Policies

### Objects
- **Users** - People accounts
- **Computers** - Machine accounts
- **Groups** - Collections of users

## AD Security
- Kerberos authentication
- LDAP for queries
- Group Policy for settings

## Common AD Tools
- **Active Directory Users and Computers** (ADUC)
- **PowerShell** (Get-ADUser, etc.)
- **dsquery** - Command line

🎯 SOC analysts must understand AD for:
- User behavior analysis
- Lateral movement detection
- Privilege escalation detection`,
                questions: [
                    ['What does AD stand for?', 'Active Directory', 'Directory service', ['Advanced Directory', 'Active Directory', 'Access Domain', 'Admin Domain']],
                    ['Which server role authenticates users in AD?', 'Domain Controller', 'Runs AD DS', ['File Server', 'Web Server', 'Domain Controller', 'DNS Server']],
                    ['What is the primary authentication protocol in AD?', 'Kerberos', 'Ticket-based', ['NTLM', 'Kerberos', 'Radius', 'LDAP']],
                    ['Which tool is commonly used to manage users and computers?', 'ADUC', 'GUI Console', ['GPMC', 'ADUC', 'DNS', 'DHCP']],
                    ['What containers are used to organize objects?', 'OUs', 'Organizational Units', ['Groups', 'Folders', 'OUs', 'Sites']]
                ]
            },
            {
                id: 36,
                title: 'PowerShell Fundamentals',
                content: `# PowerShell Fundamentals

## What is PowerShell?
Microsoft's task automation and configuration management framework.

## Key Features
- **Cmdlets** - Commands (Verb-Noun format)
- **Pipeline** - Pass objects between commands
- **Scripting** - .ps1 files
- **Remoting** - Execute on remote systems

## Basic Cmdlets
\`\`\`powershell
Get-Process              # List processes
Get-Service             # List services
Get-EventLog            # View logs
Get-ChildItem           # List files (like ls)
Get-Content             # Read file
Select-String           # Search text (like grep)
\`\`\`

## Pipeline Example
\`\`\`powershell
Get-Process | Where-Object {$_.CPU -gt 100} | Select-Object Name,CPU
\`\`\`

## Security
🚨 Attackers use PowerShell:
- Download malware
- Execute scripts
- Bypass AV
- Lateral movement

## Execution Policy
- Restricted (default)
- AllSigned
- RemoteSigned
- Unrestricted

## SOC Operations
- Log analysis
- Incident response
- Automation
- Threat hunting`,
                questions: [
                    ['What is the naming format for PowerShell cmdlets?', 'Verb-Noun', 'Action-Target', ['Verb-Noun', 'Noun-Verb', 'Action-Object', 'Subject-Predicate']],
                    ['Which cmdlet lists running processes?', 'Get-Process', 'Usage: Get-Process', ['list-proc', 'Get-Process', 'Show-Tasks', 'ps-list']],
                    ['What is the file extension for PowerShell scripts?', '.ps1', 'PowerShell 1', ['.bat', '.sh', '.ps1', '.exe']],
                    ['Which cmdlet is similar to grep?', 'Select-String', 'Search inside files', ['Find-Text', 'Grep-File', 'Select-String', 'Search-Content']],
                    ['What is the default execution policy?', 'Restricted', 'Blocks all scripts', ['Unrestricted', 'RemoteSigned', 'Restricted', 'AllSigned']]
                ]
            },
            {
                id: 37,
                title: 'Windows Event Logs',
                content: `# Windows Event Logs

## What are Event Logs?
Records of system, application, and security events.

## Main Log Types
- **Security** - Logins, privilege changes
- **System** - Hardware, drivers, services
- **Application** - Software events

## Key Event IDs

**Security Log:**
- 4624 - Successful logon
- 4625 - Failed logon
- 4672 - Admin logon
- 4768 - Kerberos ticket
- 4776 - Credential validation

**System Log:**
- 7045 - New service installed
- 1074 - System shutdown

## Viewing Logs
\`\`\`powershell
Get-EventLog -LogName Security -Newest 10
Get-WinEvent -FilterHashtable @{LogName='Security';ID=4625}
\`\`\`

## Log Location
C:\\Windows\\System32\\winevt\\Logs\\*.evtx

## SOC Use Cases
✓ Detect brute force (multiple 4625)
✓ Track privilege escalation (4672)
✓ Identify lateral movement
✓ Investigate suspicious processes`,
                questions: [
                    ['Which event ID indicates a successful logon?', '4624', 'Security Success', ['4625', '4624', '4672', '1074']],
                    ['Which event ID indicates a failed logon?', '4625', 'Security Failure', ['4624', '4625', '4768', '7045']],
                    ['Which log records login attempts?', 'Security', 'Auth events', ['System', 'Application', 'Security', 'Setup']],
                    ['Which cmdlet is used to retrieve event logs?', 'Get-EventLog', 'Old cmdlet, but common', ['Show-Logs', 'Get-EventLog', 'Read-Events', 'Fetch-Log']],
                    ['What is the file extension for event logs?', '.evtx', 'New format', ['.log', '.txt', '.evtx', '.xml']]
                ]
            },
            {
                id: 38,
                title: 'Group Policy',
                content: `# Group Policy

## What is Group Policy?
Centralized management of Windows settings across AD domain.

## Group Policy Object (GPO)
Configuration that can be applied to users/computers.

## Common GPO Settings
- Password policies
- Software installation
- Security settings
- Folder redirection
- Startup/shutdown scripts

## GPO Locations
- Local Computer Policy
- Site Policies
- Domain Policies
- OU Policies

## Order of Application (LSDOU)
1. Local
2. Site
3. Domain
4. OU

Last applied = highest priority

## Tools
- **Group Policy Management Console** (GPMC)
- **gpupdate /force** - Refresh policies
- **gpresult** - View applied policies

## Security Uses
- Enforce password complexity
- Disable USB drives
- Deploy security software
- Configure firewall
- Audit settings`,
                questions: [
                    ['What does GPO stand for?', 'Group Policy Object', 'Config object', ['General Policy Option', 'Group Policy Object', 'Global Permission Order', 'Group Permission Object']],
                    ['Which command forces a GP update?', 'gpupdate /force', 'Refresh command', ['gpupdate /force', 'gprefresh', 'update-policy', 'gpreload']],
                    ['What is the order of GPO application?', 'LSDOU', 'Local, Site, Domain, OU', ['DSOUL', 'LSDOU', 'OUDSC', 'SLDOU']],
                    ['Which tool is used to manage Group Policy?', 'GPMC', 'Management Console', ['ADUC', 'GPMC', 'DNS', 'LGP']],
                    ['Which level of GPO has the highest precedence?', 'OU', 'Applied last', ['Local', 'Site', 'Domain', 'OU']]
                ]
            },
            {
                id: 39,
                title: 'Windows Security Tools',
                content: `# Windows Security Tools

## Built-in Tools

### Windows Defender
- Real-time protection
- Cloud-delivered protection
- SmartScreen filter

### Windows Firewall
\`\`\`powershell
Get-NetFirewallRule
New-NetFirewallRule
\`\`\`

### BitLocker
- Full disk encryption
- TPM integration

## Sysinternals Suite
Essential tools from Microsoft:

**Process Explorer** - Advanced task manager
**Process Monitor** - Real-time file/registry monitoring
**Autoruns** - Startup program management
**TCPView** - Network connections
**PsExec** - Remote execution

## Security & Maintenance
- **msconfig** - Startup configuration
- **Task Scheduler** - Automated tasks
- **Event Viewer** - Log analysis
- **Resource Monitor** - System performance

## Command Line Tools
\`\`\`cmd
netstat -ano          # Network connections
tasklist /v           # Running processes
wmic process list     # Process details
net user              # User accounts
net localgroup        # Groups
\`\`\`

## SOC Toolbox
✓ Process Explorer - Malware detection
✓ Autoruns - Persistence mechanisms
✓ Event Viewer - Incident investigation
✓ netstat - Network analysis`,
                questions: [
                    ['Which built-in tool provides real-time virus protection?', 'Windows Defender', 'Antivirus', ['Windows Firewall', 'Windows Defender', 'BitLocker', 'SmartScreen']],
                    ['Which Sysinternals tool is an advanced Task Manager?', 'Process Explorer', 'Process info', ['Process Monitor', 'Autoruns', 'Process Explorer', 'PsExec']],
                    ['Which tool provides full disk encryption?', 'BitLocker', 'Disk security', ['SecureBoot', 'BitLocker', 'EFS', 'Vault']],
                    ['Which command shows active network connections?', 'netstat', 'Network statistics', ['ping', 'ipconfig', 'netstat', 'tracert']],
                    ['Which Sysinternals tool checks for auto-starting programs?', 'Autoruns', 'Persistence', ['Task Scheduler', 'Startup Manager', 'Autoruns', 'Services']]
                ]
            }
        ];

        for (const lesson of winLessons) {
            // Clean up existing content first to avoid duplicates
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [lesson.id]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [lesson.id]);

            const contentWithImage = `![Windows Security](/images/windows_security.png)\n\n${lesson.content}`;

            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [lesson.id, contentWithImage, 'markdown', 7]);

            // Limit to 3 questions max
            const maxQuestions = Math.min(lesson.questions.length, 3);
            for (let i = 0; i < maxQuestions; i++) {
                const q = lesson.questions[i];
                // q[3] contains the options array
                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 (?, ?, ?, ?, ?, ?, ?)',
                    [lesson.id, q[0], q[1], i + 1, q[2], options, 0]);
            }
            totalCreated++;
            console.log(`✓ ${lesson.title}`);
        }

        console.log(`\n✅ Windows Fundamentals complete! (${winLessons.length} lessons)\n`);
        console.log(`Total lessons created: ${totalCreated}\n`);

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

createMassLessons();
