/**
 * System Worker
 *
 * Processes system maintenance jobs:
 * - Drift detection between Prisma and Supabase
 * - Health checks
 * - Cleanup tasks
 *
 * @requires bullmq, drift-detection.service
 */

import 'server-only';
import { Worker, Job } from 'bullmq';
import { logger } from '@/lib/logger';
import { registerWorker, QUEUE_NAMES, SystemJobPayload } from '../bullmq';
import { handleDriftCheckJob } from '@/lib/jobs/handlers';

/**
 * Process system jobs
 */
async function processSystemJob(job: Job<SystemJobPayload>): Promise<void> {
  const { type, countThreshold, percentageThreshold, sendAlertEmail, metadata } = job.data;

  logger.info('[SystemWorker] Processing system job', {
    jobId: job.id,
    type,
    metadata,
  });

  switch (type) {
    case 'drift_check':
      await handleDriftCheckJob({
        countThreshold,
        percentageThreshold,
        sendAlertEmail,
      });
      break;

    case 'health_check':
      // TODO: Implement health check job if needed
      logger.info('[SystemWorker] Health check job - not implemented yet');
      break;

    case 'cleanup':
      // TODO: Implement cleanup job if needed
      logger.info('[SystemWorker] Cleanup job - not implemented yet');
      break;

    default:
      logger.warn('[SystemWorker] Unknown system job type', { type });
  }
}

/**
 * Start the system worker
 */
export function startSystemWorker(): Worker<SystemJobPayload> {
  logger.info('[SystemWorker] Starting system worker...');

  const worker = registerWorker<SystemJobPayload>(
    QUEUE_NAMES.SYSTEM,
    processSystemJob,
    {
      concurrency: 2, // System jobs are resource-intensive, limit concurrency
    }
  );

  logger.info('[SystemWorker] System worker started');

  return worker;
}
