
import cron from 'node-cron';
import Subscription from '../models/Subscription';

/**
 * Initialize the subscription expiry cron job.
 * Runs every 4 hours to check for expired subscriptions and updates their status.
 */
export const initSubscriptionCron = () => {
    // Run immediately on server start to catch missed jobs
    runSubscriptionCheck();

    // Schedule task to run at minute 0 past every 4th hour (0, 4, 8, 12, 16, 20)
    cron.schedule('0 */4 * * *', () => {
        runSubscriptionCheck();
    });

    console.log('[Cron] Subscription expiry job scheduled (runs every 4 hours).');
};

const runSubscriptionCheck = async () => {
    console.log(`[Cron] Running subscription expiry check at ${new Date().toISOString()}...`);

    try {
        const now = new Date();

        // Find all Active subscriptions where endDate is in the past
        const result = await Subscription.updateMany(
            {
                status: 'Active',
                endDate: { $lt: now }
            },
            {
                $set: {
                    status: 'Expired',
                    updatedAt: now
                }
            }
        );

        if (result.modifiedCount > 0) {
            console.log(`[Cron] Expired ${result.modifiedCount} overdue subscriptions.`);
        } else {
            console.log('[Cron] No expired subscriptions found.');
        }
    } catch (error) {
        console.error('[Cron] Error running subscription expiry check:', error);
    }
};
