/**
 * Worker Service
 * Polls Supabase queue and processes TMS permission submissions
 */

import { config } from '../config';
import { supabaseService } from './supabase.service';
import { processSubmission } from '../controllers/permission.controller';
import { logger } from '../utils/logger';

const POLL_INTERVAL = config.workerIntervalMs;
const MAX_RETRIES = config.maxRetries;

let workerInterval: NodeJS.Timeout | null = null;
let isProcessing = false;

/**
 * Process a batch of pending submissions
 */
async function processBatch(): Promise<void> {
  if (isProcessing) {
    logger.debug('Worker already processing, skipping');
    return;
  }

  try {
    isProcessing = true;

    const pendingSubmissions = await supabaseService.getPendingSubmissions();

    if (pendingSubmissions.length === 0) {
      // logger.debug('No pending submissions');
      return;
    }

    logger.debug('Processing batch', {
      count: pendingSubmissions.length,
    });

    // Process submissions sequentially
    for (const submission of pendingSubmissions) {
      try {
        await processSubmission(submission.submission_id);
      } catch (error: any) {
        logger.error('Error processing submission in batch', {
          submissionId: submission.submission_id,
          error: error.message,
        });
      }
    }
  } catch (error: any) {
    logger.error('Error in worker batch', { error: error.message });
  } finally {
    isProcessing = false;
  }
}

/**
 * Worker loop
 */
async function workerLoop(): Promise<void> {
  try {
    await processBatch();
  } catch (error: any) {
    logger.error('Error in worker loop', { error: error.message });
  }
}

/**
 * Start the worker
 */
export function startWorker(): void {
  if (workerInterval) {
    logger.warn('Worker already running');
    return;
  }

  logger.debug('🚀 Starting TMS Permission Worker', {
    pollInterval: POLL_INTERVAL,
    maxRetries: MAX_RETRIES,
  });

  // Start polling
  workerInterval = setInterval(workerLoop, POLL_INTERVAL);

  // Run immediately
  workerLoop();
}

/**
 * Stop the worker
 */
export function stopWorker(): void {
  if (workerInterval) {
    clearInterval(workerInterval);
    workerInterval = null;
    logger.debug('Worker stopped');
  }
}
