/**
 * Email Worker
 *
 * Processes email jobs from the BullMQ email queue.
 * Handles transactional emails (OTP, notifications) and marketing emails.
 *
 * Features:
 * - Automatic retries with exponential backoff
 * - Email template validation
 * - Rate limiting (100 emails/minute)
 * - Dead letter queue for failed sends
 */

import 'server-only';
import { Job } from 'bullmq';
import { registerWorker, QUEUE_NAMES, EmailJobPayload } from '../bullmq';
import { sendEmailImmediate } from '@/lib/email';
import { logger } from '@/lib/logger';

/**
 * Email job processor
 */
async function processEmailJob(job: Job<EmailJobPayload>): Promise<void> {
  const { to, subject, html, text, category, metadata } = job.data;

  logger.debug('[EmailWorker] Processing email', {
    jobId: job.id,
    to,
    subject,
    category,
    attempt: job.attemptsMade + 1,
  });

  // Validate email payload
  if (!to || !subject || (!html && !text)) {
    throw new Error('Invalid email payload: missing required fields');
  }

  // Send email via SMTP
  const success = await sendEmailImmediate(to, {
    subject,
    html,
    text,
  });

  if (!success) {
    throw new Error(`Failed to send email to ${to}`);
  }

  logger.info('[EmailWorker] Email sent successfully', {
    jobId: job.id,
    to,
    category,
    metadata,
  });
}

/**
 * Start the email worker
 */
export function startEmailWorker() {
  const worker = registerWorker<EmailJobPayload>(
    QUEUE_NAMES.EMAIL,
    processEmailJob,
    {
      concurrency: 10, // Process 10 emails concurrently
      limiter: {
        max: 100, // Max 100 emails
        duration: 60000, // Per minute
      },
    }
  );

  logger.info('[EmailWorker] Started with concurrency=10, rate=100/min');

  return worker;
}
