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

const overview = {
    id: 20,
    title: 'Social Engineering Defense',
    description: 'Understand the human element of security and how to defend against manipulation.',
    learning_path_id: 2 // Security Operations Basics
};

const tasks = [
    { id: 201, title: 'Psychology of Persuasion' },
    { id: 202, title: 'Pretexting & Impersonation' },
    { id: 203, title: 'Vishing (Voice Phishing)' },
    { id: 204, title: 'Smishing (SMS Phishing)' },
    { id: 205, title: 'Physical: Tailgating & Dumpster Diving' },
    { id: 206, title: 'Baiting & Quid Pro Quo' },
    { id: 207, title: 'Module 20 Final Quiz' }
];

const lessons = {
    201: {
        content: `# Psychology of Persuasion

Social Engineering hacks *people*, not computers. It relies on cognitive biases.

## Robert Cialdini's 6 Principles of Persuasion
Attackers use these triggers to make you bypass security protocols.

1.  **Authority**: "I am the CEO. Do this now." (Fear of disobeying).
2.  **Urgency / Scarcity**: "Your account will be deleted in 1 hour." (Panic -> Action).
3.  **Reciprocity**: "I did you a favor, now you owe me." (e.g., An attacker fixes a "problem" they caused).
4.  **Social Proof**: "Everyone else is doing it."
5.  **Liking**: The attacker is charming, funny, or attractive. (Hard to say 'no' to a friend).
6.  **Consistency**: Small requests lead to big ones. "Can you answer this survey?" -> "Can you install this software?"

## The Defense
*   **Stop and Think**: Urgency is the enemy of logic. If you feel rushed, PAUSE.
*   **Verify**: Call the person back on a known good number.`,
        questions: [
            ['Which principle relies on the target\'s fear of disobeying a superior?', 'Authority', 'Boss', ['Reciprocity', 'Authority', 'Liking', 'Consistency']],
            ['"Act now or lose your account!" exploits which psychological trigger?', 'Urgency / Scarcity', 'Panic', ['Trust', 'Urgency / Scarcity', 'Social Proof', 'Kindness']],
            ['What is the best immediate defense when you feel "rushed" by a request?', 'Stop and Verify', 'Pause', ['Do it quickly', 'Stop and Verify', 'Argue', 'Ignore it']]
        ]
    },
    202: {
        content: `# Pretexting & Impersonation

**Pretexting** is creating a fabricated scenario (the pretext) to steal information.

## The Setup
The attacker doesn't just ask for a password; they create a story.
*   *Example*: "Hi, I'm from IT Support. We're migrating the server and your account is out of sync. I need you to read me the code on your phone to resync it."
*   *The Pretext*: Server migration.
*   *The Goal*: MFA Bypass (the code).

## Impersonation Targets
1.  **IT Support**: "I'm here to fix the WiFi." (Gets access to server room).
2.  **The CEO**: "I'm in a meeting and can't talk. Wire the money."
3.  **Vendors/Partners**: "Here is the updated invoice due today."

## Defense: Challenge Questions
*   "Can you verify your ticket number?"
*   "I will call you back on the internal extension." (Attackers often hang up here).`,
        questions: [
            ['What is "Pretexting"?', 'Creating a fake scenario to trick a victim', 'Story', ['Guessing passwords', 'Creating a fake scenario to trick a victim', 'Scanning ports', 'Coding malware']],
            ['Who is a common persona for attackers to impersonate?', 'IT Support', 'Help Desk', ['The Janitor', 'IT Support', 'A stranger', 'A dog']],
            ['How do you defeat an impersonator on the phone?', 'Call them back on a verified number', 'Callback', ['Ask their name', 'Call them back on a verified number', 'Yell at them', 'Tracing the call']]
        ]
    },
    203: {
        content: `# Vishing (Voice Phishing)

**Vishing** is Phishing over the phone.

## The Deepfake Era
Historically, attackers used voice changers. Now, AI can clone a CEO's voice with 3 seconds of audio.
*   **Scenario**: You get a call from the CEO. It *sounds* like him. He knows your name. He asks you to move money.
*   **Spoofing**: The Caller ID says "Head Office". (Caller ID is easily spoofed).

## Common Tactics
*   **The "Tech Support" Scam**: "We detected a virus on your computer. Download AnyDesk so I can fix it."
*   **The IRS/Tax Scam**: "You owe taxes and the police are coming. Pay with Gift Cards."

## Indicators
*   **Demands for Remote Access**: Never let a cold-caller remote into your PC.
*   **Payment via Gift Cards**: HUGE red flag. No legitimate business asks for iTunes cards.`,
        questions: [
            ['What is "Vishing"?', 'Phishing conducted over the phone', 'Voice', ['Video Phishing', 'Phishing conducted over the phone', 'Virtual Fishing', 'Virus Phishing']],
            ['Why is Caller ID not a reliable way to verify a caller?', 'It can be easily spoofed', 'Fake numbers', ['It is encrypted', 'It can be easily spoofed', 'It costs money', 'It is old tech']],
            ['What payment method is a major red flag for scam calls?', 'Gift Cards', 'iTunes', ['Credit Card', 'Gift Cards', 'Wire Transfer', 'Check']]
        ]
    },
    204: {
        content: `# Smishing (SMS Phishing)

**Smishing** attacks you via Text Message.

## Why it works
*   **High Trusted Trust**: We trust our text messages more than email.
*   **Hard to Inspect**: You can't hover over links on a phone easily to see the true URL.
*   **Short Links**: \`bit.ly/5xf7s\` hides the destination.

## Common Lures
*   **Delivery**: "USPS: We tried to deliver your package. Click here to reschedule."
*   **Bank Alert**: "Wells Fargo: Suspicious charge of $500. Reply NO to cancel, or click here."
*   **MFA Fraud**: "Here is your code." (Sent right after the attacker tries to login).

## Prevention
*   **Never click links in SMS**. Go to the app/website directly.
*   **Report**: Forward spam texts to **7726** (SPAM) on most carriers.`,
        questions: [
            ['What makes Smishing URLs harder to inspect than email URLs?', 'Mobile interfaces make hovering/previewing difficult', 'No mouse', ['They are encrypted', 'Mobile interfaces make hovering/previewing difficult', 'They are faster', 'They are secure']],
            ['What is a common "Lure" for SMS attacks?', 'Missed package delivery', 'USPS', ['Free pizza', 'Missed package delivery', 'Weather alert', 'News update']],
            ['If you get a suspicious text from your "Bank", what should you do?', 'Log in via the official App or Website', 'Direct access', ['Click the link', 'Log in via the official App or Website', 'Reply STOP', 'Call the number in the text']]
        ]
    },
    205: {
        content: `# Physical: Tailgating & Dumpster Diving

Not all social engineering is digital.

## Tailgating (Piggybacking)
Following unauthorized behind an authorized person into a secure area.
*   **The "Help Me"**: Attacker carries a heavy box or two coffees. They rely on your politeness to hold the door.
*   **The Smoking Area**: Attacker hangs out with smokers, then walks back in with the group.
*   **Defense**: "I'm sorry, I cannot hold the door. You need to badge in." (Be polite but firm).

## Dumpster Diving
Going through trash to find information.
*   **Gold**: Org charts, phone lists, sticky notes with passwords, printed source code, vendor invoices.
*   **Defense**: **Shred** all sensitive documents. Use locked shredder bins.

## Shoulder Surfing
Looking over someone's shoulder to see their password or screen.
*   **Defense**: Privacy screens, being aware of surroundings.`,
        questions: [
            ['What constitutes "Tailgating"?', 'Following someone into a secure area without badging in', 'Piggyback', ['Driving too close', 'Following someone into a secure area without badging in', 'Breaking a lock', 'Hacking a badge reader']],
            ['How do attackers exploit "politeness" to bypass physical security?', 'Holding the door for someone carrying items', 'Heavy box', ['Buying lunch', 'Holding the door for someone carrying items', 'Saying please', 'Dressing nice']],
            ['What is the primary defense against Dumpster Diving?', 'Shredding sensitive documents', 'Shred', ['Burning trash', 'Shredding sensitive documents', 'Recycling', 'Hiding trash']]
        ]
    },
    206: {
        content: `# Baiting & Quid Pro Quo

Trading curiosity or service for access.

## Baiting
Leaving something tempting for the victim to find.
*   **USB Drops**: Leaving a USB drive labeled "Executive Salaries" or "Layoff Plan 2024" in the parking lot.
*   **Digital Bait**: A download button for "Free Movies" that contains malware.
*   **Psychology**: Curiosity. "What is on this drive?"

## Quid Pro Quo (Something for Something)
"I will help you if you help me."
*   **Scenario**: Attacker blindly calls numbers claiming to be Tech Support. Eventually, they find someone with an actual problem.
    *   *Attacker*: "I can fix that slow printer, just disable your antivirus for a second."
    *   *Victim*: Grateful for the help, complies.

## The Evil Twin (Wi-Fi Baiting)
Setting up a Free Wi-Fi hotspot named "Starbucks_Free_WiFi" to capture traffic.`,
        questions: [
            ['What is a "USB Drop" attack?', 'Leaving an infected USB drive for a victim to find', 'Bait', ['Throwing USBs at people', 'Leaving an infected USB drive for a victim to find', 'Stealing USBs', 'Buying USBs']],
            ['What human emotion does Baiting primarily exploit?', 'Curiosity', 'Wonder', ['Fear', 'Curiosity', 'Greed', 'Sadness']],
            ['How does Quid Pro Quo differ from Baiting?', 'It involves an exchange of service/help', 'Exchange', ['It is faster', 'It involves an exchange of service/help', 'It is digital only', 'It uses email']]
        ]
    },
    207: {
        content: `# Module 20 Final Quiz

Test your defenses against the human hacker.

**Instructions**:
*   20 Questions covering Psychology, Impersonation, Physical Threats, and Digital Social Engineering.`,
        questions: [
            // Psychology
            ['Which Cialdini principle explains why people comply with requests from "The CEO"?', 'Authority', 'Boss', ['Liking', 'Authority', 'Scarcity', 'Reciprocity']],
            ['If an attacker does you a favor to make you feel obligated, which principle is this?', 'Reciprocity', 'Owe me', ['Social Proof', 'Reciprocity', 'Authority', 'Commitment']],
            ['"Only 2 spots left!" is an example of:', 'Scarcity', 'Rare', ['Authority', 'Scarcity', 'Consistency', 'Liking']],

            // Pretexting / Vishing
            ['What is the best way to verify a "Bank" calling you?', 'Hang up and call the number on your card', 'Source of truth', ['Ask for their ID', 'Hang up and call the number on your card', 'Trust Caller ID', 'Ask for a supervisor']],
            ['What is "Pretexting"?', 'Creating a fabricated scenario to obtain info', 'Lying scenario', ['Using text messages', 'Creating a fabricated scenario to obtain info', 'Pre-authorized scanning', 'Testing backups']],
            ['Which technology has made Vishing much more dangerous recently?', 'AI Voice Cloning / Deepfakes', 'AI', ['5G', 'AI Voice Cloning / Deepfakes', 'Fiber Optics', 'VoIP']],

            // Smishing
            ['Why are shortened URLs (bit.ly) dangerous in SMS?', 'They hide the true destination', 'Obfuscation', ['They are slow', 'They hide the true destination', 'They cost money', 'They assume HTTP']],
            ['What is the term for Phishing via SMS?', 'Smishing', 'SMS', ['Vishing', 'Smishing', 'Phishing', 'Texting']],
            ['Where should you report spam texts?', '7726 (SPAM)', 'Carrier code', ['911', '7726 (SPAM)', 'The Police', 'Your Mom']],

            // Physical
            ['What is "Tailgating"?', 'Following an authorized person through a secure door', 'Piggybacking', ['Driving close', 'Following an authorized person through a secure door', 'Hacking the lock', 'Climbing the fence']],
            ['What is the counter-measure for "Dumpster Diving"?', 'Shredding documents', 'Destruction', ['Recycling', 'Shredding documents', 'burning', 'hiding']],
            ['What is "Shoulder Surfing"?', 'Looking at someone\'s screen/keyboard to steal info', 'Peeking', ['Massaging shoulders', 'Looking at someone\'s screen/keyboard to steal info', 'Surfing the web', 'Hacking wifi']],

            // Baiting
            ['If you find a USB drive labeled "Payroll" in the lobby, what should you do?', 'Do not plug it in; give to Security', 'Quarantine', ['Plug it in to check', 'Do not plug it in; give to Security', 'Throw it away', 'Keep it']],
            ['Establishing a fake "Free WiFi" spot to steal data is called:', 'Evil Twin', 'WiFi Clone', ['Bad Twin', 'Evil Twin', 'Good Twin', 'Rogue AP']],
            ['"Quid Pro Quo" means:', 'Something for Something', 'Exchange', ['Free for all', 'Something for Something', 'Nothing for Nothing', 'Quick Pro']],

            // General
            ['What is the weakest link in most security systems?', 'The Human', 'People', ['The Firewall', 'The Human', 'The Encryption', 'The Password']],
            ['Does Social Engineering always involve a computer?', 'No (Physical/Phone)', 'No', ['Yes', 'No (Physical/Phone)', 'Maybe', 'Only on Tuesdays']],
            ['What implies "Social Proof"?', '"9 out of 10 users did this"', 'Crowd', ['"I am the boss"', '"9 out of 10 users did this"', '"This is rare"', '"I like you"']],
            ['Why do attackers target new employees?', 'They are eager to please and don\'t know procedures', 'Newbies', ['They have more access', 'They are eager to please and don\'t know procedures', 'They make more money', 'They are dumb']],
            ['What is the best general defense against Social Engineering?', 'Security Awareness Training & skepticism', 'Training', ['Better Firewalls', 'Security Awareness Training & skepticism', 'More Antivirus', 'Blocking Email']]
        ]
    }
};

async function createModule20() {
    try {
        console.log('🚀 Creating Module 20: Social Engineering Defense...\n');

        // Create Module (Path 2: Security Operations Basics)
        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, 20, 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]);

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

            // Insert Questions
            for (let j = 0; j < lesson.questions.length; 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]);
            }
            totalLessons++;
        }

        console.log(`\n✅ Module 20 (Social Engineering) Created! (${totalLessons} lessons)\n`);
        process.exit(0);

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

createModule20();
