const cron = require('node-cron');
const GroupCleanupService = require('./GroupCleanupService');

class SchedulerService {
    constructor() {
        this.tasks = [];
    }

    start() {
        console.log('[Scheduler] Starting scheduled tasks...');

        // Cleanup-Job: Jeden Tag um 10:00 Uhr
        const cleanupTask = cron.schedule('0 10 * * *', async () => {
            console.log('[Scheduler] Running daily cleanup at 10:00 AM...');
            try {
                await GroupCleanupService.performScheduledCleanup();
            } catch (error) {
                console.error('[Scheduler] Cleanup task failed:', error);
            }
        }, {
            scheduled: true,
            timezone: "Europe/Berlin" // Anpassen nach Bedarf
        });

        this.tasks.push(cleanupTask);

        console.log('✓ Scheduler started - Daily cleanup at 10:00 AM (Europe/Berlin)');
        
        // Für Development: Manueller Trigger
        if (process.env.NODE_ENV === 'development') {
            console.log('📝 Development Mode: Use GroupCleanupService.performScheduledCleanup() to trigger manually');
        }
    }

    stop() {
        console.log('[Scheduler] Stopping all scheduled tasks...');
        this.tasks.forEach(task => task.stop());
        this.tasks = [];
        console.log('✓ Scheduler stopped');
    }

    // Für Development: Manueller Cleanup-Trigger
    async triggerCleanupNow() {
        console.log('[Scheduler] Manual cleanup triggered...');
        return await GroupCleanupService.performScheduledCleanup();
    }
}

module.exports = new SchedulerService();
