import { Job } from 'bullmq';
import { pauseService } from '../services/pause.service';
import logger from '../utils/logger';

export async function handlePauseResumeJob(job: Job): Promise<void> {
  try {
    const { type, requestId, levelId, scheduledResumeDate } = job.data;
    
    if (type === 'auto-resume-workflow') {
      // Dedicated job to resume a specific workflow at scheduled time
      logger.info(`[Pause Resume Processor] Processing dedicated auto-resume job ${job.id} for workflow ${requestId}`);
      
      try {
        await pauseService.resumeWorkflow(requestId);
        logger.info(`[Pause Resume Processor] ✅ Auto-resumed workflow ${requestId} (scheduled for ${scheduledResumeDate})`);
      } catch (resumeError: any) {
        logger.error(`[Pause Resume Processor] Failed to auto-resume workflow ${requestId}:`, resumeError?.message || resumeError);
        throw resumeError; // Re-throw to trigger retry
      }
    } else if (type === 'check_and_resume') {
      // Legacy: Hourly check job for all paused workflows (fallback)
      logger.info(`[Pause Resume Processor] Processing bulk auto-resume check job ${job.id}`);
      const resumedCount = await pauseService.checkAndResumePausedWorkflows();
      
      if (resumedCount > 0) {
        logger.info(`[Pause Resume Processor] Auto-resumed ${resumedCount} workflow(s) via bulk check`);
      } else {
        logger.debug('[Pause Resume Processor] No workflows to auto-resume');
      }
    } else {
      logger.warn(`[Pause Resume Processor] Unknown job type: ${type}`);
    }
  } catch (error: any) {
    logger.error(`[Pause Resume Processor] Failed to process job ${job.id}:`, error?.message || error);
    throw error; // Re-throw to trigger retry mechanism
  }
}

