const cron = require('node-cron');
const leaderboardService = require('../services/leaderboardService');
const blogAutomationService = require('../services/blogAutomationService');
const adminController = require('../controllers/adminController');

const initCronJobs = () => {
    // If running in a cluster (PM2/Passenger), only run crons on instance 0
    if (process.env.NODE_APP_INSTANCE && process.env.NODE_APP_INSTANCE !== '0') {
        console.log(`[Cron] Skipping initialization on instance ${process.env.NODE_APP_INSTANCE}`);
        return;
    }

    console.log('Initializing Cron Jobs...');

    // Schedule: At 00:00 on day-of-month 1 (Monthly Reset)
    cron.schedule('0 0 1 * *', async () => {
        console.log('[Cron] Running Monthly Leaderboard Reset & Awards...');
        try {
            // 1. Award Top 3 Winners of the previous month
            console.log('[Cron] Awarding Top 3 Users...');
            await leaderboardService.awardTop3();
            console.log('[Cron] Awards distributed successfully.');

            // 2. Reset the Leaderboard
            console.log('[Cron] Resetting Leaderboard...');
            await leaderboardService.resetLeaderboard();
            console.log('[Cron] Leaderboard reset successfully.');
            
        } catch (error) {
            console.error('[Cron] Error during monthly leaderboard processing:', error);
        }
    }, { recoverMissedExecutions: false });

    // Schedule: Daily Blog Automation (Trend Discovery & Drafting) at 09:00 AM
    cron.schedule('0 9 * * *', async () => {
        console.log('🤖 Auto-Blogger: Cron Triggered.');
        await blogAutomationService.runScheduledTask();
    }, { recoverMissedExecutions: false });

    // Schedule: Daily Unverified User Cleanup at 01:00 AM
    cron.schedule('0 1 * * *', async () => {
        console.log('[Cron] Running Daily Unverified User Cleanup...');
        try {
            const result = await adminController.performUnverifiedCleanup();
            console.log(`[Cron] Cleanup complete: ${result.accountsDeleted} deleted, ${result.remindersSent} reminded.`);
        } catch (error) {
            console.error('[Cron] Error during unverified user cleanup:', error);
        }
    }, { recoverMissedExecutions: false });

    console.log('Cron Jobs Initialized: Monthly Reset, Auto-Blogger & Cleanup active.');
};

module.exports = initCronJobs;
