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

const baseStyles = `
    body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #0e0f11; margin: 0; padding: 0; color: #e0e0e0; }
    .container { max-width: 600px; margin: 0 auto; background-color: #1a1b1e; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.5); border: 1px solid #333; }
    .header { background: linear-gradient(90deg, #1a1b1e 0%, #2c0b4a 100%); padding: 30px 40px; border-bottom: 1px solid #333; text-align: center; }
    .logo { color: #00ff41; font-size: 24px; font-weight: 800; letter-spacing: 2px; text-transform: uppercase; text-shadow: 0 0 10px rgba(0, 255, 65, 0.3); margin: 0; }
    .logo span { color: #b026ff; }
    .content { padding: 40px; line-height: 1.6; }
    .h1 { color: #ffffff; margin-top: 0; font-size: 24px; margin-bottom: 20px; }
    .card { background-color: #131416; border-left: 4px solid #b026ff; padding: 20px; margin: 20px 0; border-radius: 4px; }
    .button { display: inline-block; background: linear-gradient(135deg, #b026ff 0%, #7928ca 100%); color: white !important; padding: 14px 30px; text-decoration: none; border-radius: 8px; font-weight: bold; margin-top: 20px; text-transform: uppercase; font-size: 14px; letter-spacing: 1px; box-shadow: 0 4px 15px rgba(176, 38, 255, 0.4); }
    .footer { background-color: #0e0f11; padding: 30px; text-align: center; font-size: 12px; color: #666; border-top: 1px solid #333; }
    .stat-row { display: flex; justify-content: space-between; margin-bottom: 10px; border-bottom: 1px solid #333; padding-bottom: 10px; }
    .stat-label { color: #888; }
    .stat-value { color: #fff; font-weight: bold; }
    .highlight { color: #00ff41; }
`;

const wrap = (title, bodyContent) => `
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>${baseStyles.replace(/\s+/g, ' ')}</style>
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="{{baseUrl}}/logo.png" alt="InfoSecLabs" style="height: 40px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;">
        </div>
        <div class="content">
            <h1 class="h1">${title}</h1>
            ${bodyContent}
        </div>
        <div class="footer">
            <p>&copy; ${new Date().getFullYear()} InfoSecLabs Platform. All rights reserved.</p>
            <p>Secure Simulation Environment // Authorized Personnel Only</p>
        </div>
    </div>
</body>
</html>`.replace(/[\r\n]+/g, '').replace(/\s{2,}/g, ' ');

const templates = {
    // 1. Email Verification
    verify_email_subject: 'Action Required: Verify Your Identity',
    verify_email_body: wrap('Verify Your Account', `
        <p>Welcome, Analyst.</p>
        <p>To initialize your secure workspace and begin your training simulations, you must verify this communication channel.</p>
        <div class="card">
            <p style="margin:0; color:#aaa; font-size:12px; text-transform:uppercase;">Action Required</p>
            <p style="margin:5px 0 0 0; color:#fff;">Click the button below to activate your clearance.</p>
        </div>
        <div style="text-align: center;">
            <a href="{{link}}" class="button">Verify Email</a>
        </div>
        <p style="font-size: 12px; color: #666; margin-top: 30px;">Direct uplink: <br><a href="{{link}}" style="color: #666;">{{link}}</a></p>
    `.replace(/[\r\n]+/g, '').replace(/\s{2,}/g, ' ')),

    // 2. Password Reset
    password_reset_subject: 'Security Alert: Password Reset Request',
    password_reset_body: wrap('Password Reset Protocol', `
        <p>We received a request to reset the credentials for your account.</p>
        <div class="card" style="border-left-color: #fca5a5;">
            <p style="margin:0; color:#f87171; font-weight:bold;">Expiration Warning</p>
            <p style="margin:5px 0 0 0; color:#fff;">This secure link expires in 60 minutes.</p>
        </div>
        <p>If you did not initiate this request, immediate perimeter checks are recommended.</p>
        <div style="text-align: center;">
            <a href="{{link}}" class="button" style="background: linear-gradient(135deg, #ef4444 0%, #b91c1c 100%); box-shadow: 0 4px 15px rgba(239, 68, 68, 0.4);">Reset Password</a>
        </div>
    `.replace(/[\r\n]+/g, '').replace(/\s{2,}/g, ' ')),

    // 3. Welcome
    welcome_email_subject: 'Deployment Authorized: Welcome to InfoSecLabs',
    welcome_email_body: wrap('Deployment Authorized', `
        <p>Analyst credentials active.</p>
        <p>Your objective is to investigate realistic cyber threats, analyze logs, and defend the network. Every correct verdict improves your rank on the global leaderboard.</p>
        <div class="card" style="border-left-color: #00ff41;">
            <p style="margin:0; color:#00ff41; font-weight:bold;">Mission Brief</p>
            <ul style="margin:10px 0 0 0; padding-left:20px; color:#ddd;">
                <li>Investigate Incidents</li>
                <li>Earn XP & Badges</li>
                <li>Competite with Top Analysts</li>
            </ul>
        </div>
        <div style="text-align: center;">
            <a href="{{link}}" class="button">Access Dashboard</a>
        </div>
    `.replace(/[\r\n]+/g, '').replace(/\s{2,}/g, ' ')),

    // 4. Alert Assigned
    alert_assigned_subject: 'New Mission: {{title}}',
    alert_assigned_body: wrap('New Incident Assigned', `
        <p>Hello <strong>{{name}}</strong>,</p>
        <p>A new security incident has been flagged and assigned to you for immediate analysis.</p>
        <div class="card">
            <p style="margin:0; color:#aaa; font-size:12px; uppercase;">Incident Details</p>
            <h3 style="margin:5px 0; color:#fff; font-size:18px;">{{title}}</h3>
            <p style="margin:0; color:#b026ff; font-weight:bold;">Status: Pending Investigation</p>
        </div>
        <p>Review logs and submit your verdict.</p>
        <div style="text-align: center;">
            <a href="{{baseUrl}}/dashboard" class="button">Start Investigation</a>
        </div>
    `.replace(/[\r\n]+/g, '').replace(/\s{2,}/g, ' ')),

    // 5. Investigation Graded
    investigation_graded_subject: 'Report Graded: {{title}}',
    investigation_graded_body: wrap('Performance Review', `
        <p>Your investigation report for <strong>{{title}}</strong> has been audited.</p>
        <div style="background-color: #131416; border: 1px solid #333; border-radius: 8px; padding: 20px; text-align: center; margin: 20px 0;">
            <p style="margin:0; color:#aaa; font-size:12px; text-transform:uppercase; letter-spacing:1px;">Final Grade</p>
            <h2 style="margin:10px 0; font-size:48px; color: #{{gradeColor}};">{{grade}}</h2>
        </div>
        <div class="card" style="border-left: 4px solid #{{gradeColor}};">
            <p style="margin:0; color:#aaa; font-size:12px;">Auditor Feedback</p>
            <p style="margin:5px 0 0 0; color:#fff; font-style:italic;">"{{feedback}}"</p>
        </div>
        <div style="text-align: center;">
            <a href="{{baseUrl}}/dashboard" class="button">View Full Details</a>
        </div>
    `.replace(/[\r\n]+/g, '').replace(/\s{2,}/g, ' ')),

    // 6. Award Won
    award_won_subject: 'Achievement Unlocked: {{awardType}} Award',
    award_won_body: wrap('Achievement Unlocked', `
        <div style="text-align: center; margin-bottom: 20px;">
            <div style="font-size: 64px;">🏆</div>
        </div>
        <p style="text-align: center; font-size: 18px;">Congratulations, <strong>{{name}}</strong>!</p>
        <p style="text-align: center;">You have earned the <strong>{{awardType}} Tier Analyst</strong> award.</p>
        <div class="card" style="border-left-color: #f59e0b; text-align: center;">
            <p style="color: #fff;">This badge has been added to your profile as a testament to your elite status.</p>
        </div>
        <div style="text-align: center;">
            <a href="{{baseUrl}}/profile" class="button" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); box-shadow: 0 4px 15px rgba(245, 158, 11, 0.4);">View Profile</a>
        </div>
    `.replace(/[\r\n]+/g, '').replace(/\s{2,}/g, ' ')),

    // 7. NEW: Weekly Report
    weekly_report_subject: 'Weekly Analyst Report',
    weekly_report_body: `
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; background-color: #0e0f11; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
    <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #0e0f11; padding: 40px 20px;">
        <tr>
            <td align="center">
                <table width="600" cellpadding="0" cellspacing="0" style="max-width: 600px;">
                    <!-- Header -->
                    <tr>
                        <td style="text-align: center; padding-bottom: 30px;">
                            <img src="https://infoseclabs.io/logo.png?v=2" alt="InfoSecLabs" style="height: 40px; margin-bottom: 20px; background-color: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px;">
                            <h1 style="color: #ffffff; font-size: 28px; margin: 0 0 10px 0;">Weekly Analyst Report</h1>
                            <p style="color: #888; font-size: 14px; margin: 0;">Performance Metrics & Activity Summary</p>
                        </td>
                    </tr>
                    
                    <!-- Greeting -->
                    <tr>
                        <td style="padding: 20px 0;">
                            <p style="color: #cccccc; font-size: 15px; margin: 0; text-align: center;">
                                Hello {{name}}, 👋<br><br>
                                Here is your performance summary for this week.
                            </p>
                        </td>
                    </tr>
                    
                    <!-- This Week Stats -->
                    <tr>
                        <td style="background-color: #1a1b1e; border-radius: 12px; padding: 25px; margin-bottom: 20px; display: block;">
                            <div style="border-bottom: 1px solid #2a2a3e; padding-bottom: 15px; margin-bottom: 20px;">
                                <span style="color: #b026ff; font-weight: bold; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">📅 This Week's Activity</span>
                            </div>
                            
                            <table width="100%" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td width="50%" style="padding-bottom: 15px;">
                                        <p style="margin:0; color:#888; font-size:12px;">Alerts Assigned</p>
                                        <p style="margin:5px 0 0 0; color:#fff; font-size:20px; font-weight:bold;">{{assigned}}</p>
                                    </td>
                                    <td width="50%" style="padding-bottom: 15px;">
                                        <p style="margin:0; color:#888; font-size:12px;">Investigations Closed</p>
                                        <p style="margin:5px 0 0 0; color:#fff; font-size:20px; font-weight:bold;">{{graded}}</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td width="50%">
                                        <p style="margin:0; color:#888; font-size:12px;">Average Score</p>
                                        <p style="margin:5px 0 0 0; color:#00ff41; font-size:20px; font-weight:bold;">{{avgScore}}%</p>
                                    </td>
                                    <td width="50%">
                                        <p style="margin:0; color:#888; font-size:12px;">XP Earned</p>
                                        <p style="margin:5px 0 0 0; color:#b026ff; font-size:20px; font-weight:bold;">+{{totalScore}} XP</p>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <!-- All Time Stats -->
                    <tr>
                        <td style="background-color: #1a1b1e; border-radius: 12px; padding: 25px; display: block; margin-top: 20px;">
                            <div style="border-bottom: 1px solid #2a2a3e; padding-bottom: 15px; margin-bottom: 20px;">
                                <span style="color: #00ff41; font-weight: bold; font-size: 14px; text-transform: uppercase; letter-spacing: 1px;">🏆 Career Performance</span>
                            </div>
                            
                            <table width="100%" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td width="33%" style="padding-bottom: 20px;">
                                        <p style="margin:0; color:#888; font-size:11px;">Total Investigations</p>
                                        <p style="margin:5px 0 0 0; color:#fff; font-size:18px; font-weight:bold;">{{totalInvestigations}}</p>
                                    </td>
                                    <td width="33%" style="padding-bottom: 20px;">
                                        <p style="margin:0; color:#888; font-size:11px;">Total XP</p>
                                        <p style="margin:5px 0 0 0; color:#fff; font-size:18px; font-weight:bold;">{{totalXP}}</p>
                                    </td>
                                    <td width="33%" style="padding-bottom: 20px;">
                                        <p style="margin:0; color:#888; font-size:11px;">Best Score</p>
                                        <p style="margin:5px 0 0 0; color:#f59e0b; font-size:18px; font-weight:bold;">{{bestScore}}</p>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="3" style="background-color: #0e0f11; border-radius: 8px; padding: 15px; text-align: center;">
                                        <p style="margin:0; color:#888; font-size:12px; margin-bottom: 5px;">Current Leaderboard Rank</p>
                                        <p style="margin:0; color:#b026ff; font-size:24px; font-weight:bold;">{{rank}}</p>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    
                    <!-- CTA -->
                    <tr>
                        <td style="text-align: center; padding: 40px 0;">
                            <a href="{{baseUrl}}/dashboard" style="display: inline-block; background: linear-gradient(135deg, #b026ff, #6366f1); color: white; text-decoration: none; padding: 14px 30px; border-radius: 8px; font-weight: 600; font-size: 15px; box-shadow: 0 4px 15px rgba(99, 102, 241, 0.4);">
                                Go to Dashboard →
                            </a>
                        </td>
                    </tr>
                    
                    <!-- Footer -->
                    <tr>
                        <td style="text-align: center; padding-top: 30px; border-top: 1px solid #2a2a3e;">
                            <p style="color: #666; font-size: 12px; margin: 0;">
                                You are receiving this report as part of your active analyst status.<br>
                                <a href="{{baseUrl}}/profile" style="color: #888; text-decoration: none;">Manage Notifications</a>
                            </p>
                            <p style="color: #444; font-size: 11px; margin-top: 10px;">
                                &copy; ${new Date().getFullYear()} InfoSecLabs Platform
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
    `
};

const seedTemplates = async () => {
    try {
        console.log('--- SEEDING EMAIL TEMPLATES ---');
        // Small delay to ensure DB connection if run immediately
        await new Promise(resolve => setTimeout(resolve, 1000));

        for (const [key, value] of Object.entries(templates)) {
            // Check if exists
            const existing = await db.query("SELECT `key` FROM system_settings WHERE `key` = ?", [key]);

            if (existing.rows.length > 0) {
                console.log(`Updating existing template: ${key}`);
                await db.query("UPDATE system_settings SET value = ?, updated_at = NOW() WHERE `key` = ?", [JSON.stringify(value), key]);
            } else {
                console.log(`Creating new template: ${key}`);
                await db.query("INSERT INTO system_settings (`key`, value, category) VALUES (?, ?, 'email_template')", [key, JSON.stringify(value)]);
            }
        }

        if (require.main === module) {
            console.log('✅ Email templates successfully seeded.');
            process.exit(0);
        } else {
            console.log('✅ Email templates successfully seeded.');
        }
    } catch (error) {
        console.error('❌ Error seeding email templates:', error);
        if (require.main === module) process.exit(1);
    }
};

if (require.main === module) {
    seedTemplates();
}

module.exports = seedTemplates;
