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

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

    start() {
        // Don't start scheduler in test mode
        if (process.env.NODE_ENV === 'test') {
            console.log('[Scheduler] Skipped in test mode');
            return;
        }

        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);

        // Telegram Warning-Job: Jeden Tag um 09:00 Uhr (1 Stunde vor Cleanup)
        const telegramWarningTask = cron.schedule('0 9 * * *', async () => {
            console.log('[Scheduler] Running daily Telegram deletion warning at 09:00 AM...');
            try {
                if (this.telegramService.isAvailable()) {
                    const groupsForDeletion = await GroupCleanupService.findGroupsForDeletion();
                    
                    if (groupsForDeletion && groupsForDeletion.length > 0) {
                        await this.telegramService.sendDeletionWarning(groupsForDeletion);
                        console.log(`[Scheduler] Sent deletion warning for ${groupsForDeletion.length} groups`);
                    } else {
                        console.log('[Scheduler] No groups pending deletion');
                    }
                } else {
                    console.log('[Scheduler] Telegram service not available, skipping warning');
                }
            } catch (error) {
                console.error('[Scheduler] Telegram warning task failed:', error);
            }
        }, {
            scheduled: true,
            timezone: "Europe/Berlin"
        });

        this.tasks.push(telegramWarningTask);

        console.log('✓ Scheduler started:');
        console.log('  - Daily cleanup at 10:00 AM (Europe/Berlin)');
        console.log('  - Daily Telegram warning at 09: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();
    }

    // Für Development: Manueller Telegram-Warning-Trigger
    async triggerTelegramWarningNow() {
        console.log('[Scheduler] Manual Telegram warning triggered...');
        try {
            if (!this.telegramService.isAvailable()) {
                console.log('[Scheduler] Telegram service not available');
                return { success: false, message: 'Telegram service not available' };
            }

            const groupsForDeletion = await GroupCleanupService.findGroupsForDeletion();
            
            if (!groupsForDeletion || groupsForDeletion.length === 0) {
                console.log('[Scheduler] No groups pending deletion');
                return { success: true, message: 'No groups pending deletion', groupCount: 0 };
            }

            await this.telegramService.sendDeletionWarning(groupsForDeletion);
            console.log(`[Scheduler] Sent deletion warning for ${groupsForDeletion.length} groups`);
            
            return { 
                success: true, 
                message: `Warning sent for ${groupsForDeletion.length} groups`,
                groupCount: groupsForDeletion.length,
                groups: groupsForDeletion.map(g => ({
                    groupId: g.groupId,
                    name: g.name,
                    year: g.year,
                    uploadDate: g.uploadDate
                }))
            };
        } catch (error) {
            console.error('[Scheduler] Manual Telegram warning failed:', error);
            return { success: false, message: error.message };
        }
    }
}

module.exports = new SchedulerService();
