import { pauseResumeQueue } from '../queues/pauseResumeQueue';
import logger from '../utils/logger';

export class PauseResumeSchedulerService {
  /**
   * Schedule the recurring auto-resume check job
   * This creates a repeating job that runs every hour
   */
  async scheduleAutoResumeJob(): Promise<void> {
    try {
      // Check if pauseResumeQueue is available
      if (!pauseResumeQueue) {
        logger.warn(`[Pause Resume Scheduler] Queue not available (Redis not connected). Skipping job scheduling.`);
        return;
      }

      // Check if job already exists
      const existingJobs = await pauseResumeQueue.getJobs(['delayed', 'waiting', 'active']);
      const autoResumeJob = existingJobs.find(job => job.name === 'check_and_resume' && job.data.type === 'check_and_resume');
      
      if (autoResumeJob) {
        logger.info('[Pause Resume Scheduler] Auto-resume job already scheduled');
        return;
      }

      // Calculate delay until next hour (e.g., if it's 2:30 PM, delay is 30 minutes)
      const now = new Date();
      const nextHour = new Date(now);
      nextHour.setHours(nextHour.getHours() + 1);
      nextHour.setMinutes(0);
      nextHour.setSeconds(0);
      nextHour.setMilliseconds(0);
      
      const delayMs = nextHour.getTime() - now.getTime();
      
      // Schedule the first job to run at the next hour
      await pauseResumeQueue.add(
        'check_and_resume',
        { type: 'check_and_resume' },
        {
          delay: delayMs,
          jobId: 'pause-resume-recurring',
          repeat: {
            pattern: '0 * * * *', // Every hour at minute 0 (cron pattern)
            tz: 'Asia/Kolkata' // Adjust timezone as needed
          },
          removeOnComplete: {
            age: 86400, // Keep for 24 hours
            count: 1000
          },
          removeOnFail: false
        }
      );

      logger.info(`[Pause Resume Scheduler] ✅ Auto-resume job scheduled (runs every hour, first run in ${Math.round(delayMs / 1000 / 60)} minutes)`);
    } catch (error) {
      logger.error(`[Pause Resume Scheduler] Failed to schedule auto-resume job:`, error);
      throw error;
    }
  }

  /**
   * Cancel the auto-resume recurring job
   */
  async cancelAutoResumeJob(): Promise<void> {
    try {
      if (!pauseResumeQueue) {
        logger.warn(`[Pause Resume Scheduler] Queue not available. Skipping job cancellation.`);
        return;
      }

      const job = await pauseResumeQueue.getJob('pause-resume-recurring');
      if (job) {
        await job.remove();
        logger.info('[Pause Resume Scheduler] Cancelled auto-resume job');
      }
    } catch (error) {
      logger.error(`[Pause Resume Scheduler] Failed to cancel auto-resume job:`, error);
    }
  }
}

export const pauseResumeSchedulerService = new PauseResumeSchedulerService();

