const cron = require('node-cron');
const db = require('../db');
const { sendEmail, sendComplimentaryReminderEmail } = require('../utils/emailService');
const { iosOnboardingTemplate } = require('../utils/emailTemplates/iosOnboarding');
const { mobileInactivityTemplate } = require('../utils/emailTemplates/mobileInactivity');

/**
 * Initializes all background automated email jobs.
 */
const startEmailJobs = () => {
    
    console.log('[CRON] Starting Email Background Jobs...');

    // Run every 15 minutes (original config)
    cron.schedule('*/15 * * * *', async () => {
        try {
            console.log('[CRON] Running iOS Onboarding check...');
            
            // Find users who registered on iOS, haven't been sent the email, and are older than 1 hour (but maybe restrict to past 24 hours to avoid spamming really old users if this ran retrospectively)
            const query = `
                SELECT id, name, email 
                FROM users 
                WHERE registration_source = 'ios' 
                AND ios_onboarding_sent = FALSE 
                AND created_at <= (NOW() - INTERVAL 1 HOUR)
                AND created_at >= (NOW() - INTERVAL 48 HOUR)
            `;
            
            const result = await db.query(query);
            const eligibleUsers = result.rows || result[0]; // Compatibility with pg/mysql arrays

            if (!eligibleUsers || eligibleUsers.length === 0) {
                return;
            }

            console.log(`[CRON] Found ${eligibleUsers.length} iOS users eligible for onboarding email.`);

            for (const user of eligibleUsers) {
                try {
                    // Generate HTML
                    const htmlContent = iosOnboardingTemplate(user.name);

                    // Send Email
                    await sendEmail(
                        user.email,
                        'Unlock Your Full InfoSecLabs Command Center',
                        htmlContent
                    );

                    // Mark as sent
                    await db.query(
                        'UPDATE users SET ios_onboarding_sent = TRUE WHERE id = ?',
                        [user.id]
                    );

                    console.log(`[CRON] Successfully sent iOS onboarding to ${user.email}`);

                } catch (emailErr) {
                    console.error(`[CRON] Failed to send onboarding to ${user.email}:`, emailErr);
                    // We DO NOT update ios_onboarding_sent here so it can retry later
                }
            }

        } catch (error) {
            console.error('[CRON] Critical error in iOS Onboarding job:', error);
        }
    }, { recoverMissedExecutions: false });

    // Run every hour to check for 3-day inactive mobile users
    cron.schedule('0 * * * *', async () => {
        try {
            console.log('[CRON] Running Mobile 3-Day Inactivity check...');
            
            // Find mobile users who registered 3-4 days ago, have NO completed tasks, and haven't received reminder
            const query = `
                SELECT u.id, u.name, u.email 
                FROM users u
                LEFT JOIN user_task_progress utp ON u.id = utp.user_id AND utp.completed = 1
                WHERE u.registration_source IN ('ios', 'android')
                AND u.mobile_reminder_sent = FALSE 
                AND u.created_at <= (NOW() - INTERVAL 3 DAY)
                AND u.created_at >= (NOW() - INTERVAL 4 DAY)
                AND utp.id IS NULL
            `;
            
            const result = await db.query(query);
            const eligibleUsers = result.rows || result[0];

            if (!eligibleUsers || eligibleUsers.length === 0) {
                return;
            }

            console.log(`[CRON] Found ${eligibleUsers.length} mobile users eligible for 3-day reminder.`);

            for (const user of eligibleUsers) {
                try {
                    const htmlContent = mobileInactivityTemplate(user.name);

                    await sendEmail(
                        user.email,
                        'InfoSecLabs | Your Training Awaits',
                        htmlContent
                    );

                    await db.query(
                        'UPDATE users SET mobile_reminder_sent = TRUE WHERE id = ?',
                        [user.id]
                    );

                    console.log(`[CRON] Successfully sent mobile 3-day reminder to ${user.email}`);

                } catch (emailErr) {
                    console.error(`[CRON] Failed to send 3-day reminder to ${user.email}:`, emailErr);
                }
            }

        } catch (error) {
            console.error('[CRON] Critical error in Mobile Inactivity job:', error);
        }
    }, { recoverMissedExecutions: false });
    
    // Run daily at 1:00 AM to check for complimentary subscription expiration and reminders
    cron.schedule('0 1 * * *', async () => {
        try {
            console.log('[CRON] Running Complimentary Pro Management check...');

            // 1. Auto-Revert Expired Complimentary Users
            // Note: We check if end_date has passed AND source is 'complimentary'
            const revertQuery = `
                SELECT id, email, name, role 
                FROM users 
                WHERE subscription_plan = 'pro' 
                AND subscription_source = 'complimentary' 
                AND subscription_end_date <= NOW()
            `;
            const revertRes = await db.query(revertQuery);
            const expiredUsers = revertRes.rows || revertRes[0] || [];

            if (expiredUsers.length > 0) {
                console.log(`[CRON] Found ${expiredUsers.length} expired complimentary users. Reverting to Free.`);
                for (const user of expiredUsers) {
                    let newRole = user.role;
                    if (newRole === 'pro') newRole = 'normal';
                    
                    await db.query(
                        "UPDATE users SET subscription_plan = 'free', subscription_status = 'inactive', subscription_source = NULL, role = ? WHERE id = ?",
                        [newRole, user.id]
                    );
                    
                    console.log(`[CRON] Successfully reverted ${user.email} to Free.`);
                    // Optional: Send "Your trial expired" email here? User didn't ask for it, but common practice.
                }
            }

            // 2. Send 24-Hour Expiration Reminders
            // We check for users whose subscription_end_date is between 23 and 25 hours from now
            // To prevent double-sending, we track 'complimentary_reminder_sent' (optional but safer)
            // Or just check exactly for a window.
            const reminderQuery = `
                SELECT id, email, name 
                FROM users 
                WHERE subscription_plan = 'pro' 
                AND subscription_source = 'complimentary' 
                AND subscription_end_date > NOW() 
                AND subscription_end_date <= (NOW() + INTERVAL 25 HOUR)
                AND subscription_end_date >= (NOW() + INTERVAL 23 HOUR)
            `;
            // Note: If you want to be extra safe, add a column 'comp_reminder_sent' to users.
            // For now, let's assume this runs daily and the window is enough.
            
            const reminderRes = await db.query(reminderQuery);
            const soonToExpire = reminderRes.rows || reminderRes[0] || [];

            if (soonToExpire.length > 0) {
                console.log(`[CRON] Found ${soonToExpire.length} complimentary users due for 24h reminder.`);
                for (const user of soonToExpire) {
                    try {
                        await sendComplimentaryReminderEmail(user.email, user.name, user.id);
                        console.log(`[CRON] Sent 24h reminder to ${user.email}`);
                    } catch (err) {
                        console.error(`[CRON] Failed to send reminder to ${user.email}:`, err);
                    }
                }
            }

        } catch (error) {
            console.error('[CRON] Critical error in Complimentary Management job:', error);
        }
    }, { recoverMissedExecutions: false });
};

module.exports = {
    startEmailJobs
};
