import { Worker, type Job } from 'bullmq';

import type { ConnectionOptions } from 'bullmq';
import { logger } from '@/lib/logger';
import { QUEUE_CONFIGS } from '@/lib/queue';

export const emailWorker = new Worker(
  'email',
  async (job: Job) => {
    logger.info({ jobId: job.id, jobName: job.name }, 'Processing email job');
    switch (job.name) {
      case 'inbox-sync': {
        const { accountId } = job.data as { accountId: string };
        const { syncInbox } = await import('@/lib/services/email-threads.service');
        await syncInbox(accountId);
        break;
      }
      case 'send-inquiry-confirmation': {
        const { to, firstName, mooringNumber, contactEmail } = job.data as {
          to: string;
          firstName: string;
          mooringNumber: string | null;
          contactEmail: string;
        };
        const { inquiryClientConfirmation } =
          await import('@/lib/email/templates/inquiry-client-confirmation');
        const { sendEmail } = await import('@/lib/email/index');
        const email = inquiryClientConfirmation({ firstName, mooringNumber, contactEmail });
        await sendEmail(to, email.subject, email.html, undefined, email.text);
        break;
      }
      case 'send-inquiry-sales-notification': {
        const { to, fullName, email, phone, mooringNumber, crmUrl } = job.data as {
          to: string;
          fullName: string;
          email: string;
          phone: string;
          mooringNumber: string | null;
          crmUrl: string;
        };
        const { inquirySalesNotification } =
          await import('@/lib/email/templates/inquiry-sales-notification');
        const { sendEmail } = await import('@/lib/email/index');
        const notification = inquirySalesNotification({
          fullName,
          email,
          phone,
          mooringNumber,
          crmUrl,
        });
        await sendEmail(to, notification.subject, notification.html, undefined, notification.text);
        break;
      }
      default:
        logger.warn({ jobName: job.name }, 'Unknown email job');
    }
  },
  {
    connection: { url: process.env.REDIS_URL! } as ConnectionOptions,
    concurrency: QUEUE_CONFIGS.email.concurrency,
  },
);

emailWorker.on('failed', (job, err) => {
  logger.error({ jobId: job?.id, jobName: job?.name, err }, 'Email job failed');
});
