import { Worker, type Job } from 'bullmq';
import { env } from '@/lib/env';

import type { ConnectionOptions } from 'bullmq';
import { logger } from '@/lib/logger';
import { attachWorkerAudit } from '@/lib/queue/audit-helpers';
import { QUEUE_CONFIGS } from '@/lib/queue';

export const exportWorker = new Worker(
  'export',
  async (job: Job) => {
    logger.info({ jobId: job.id, jobName: job.name }, 'Processing export job');
    switch (job.name) {
      case 'gdpr-export': {
        const data = job.data as {
          exportId: string;
          portId: string;
          clientId: string;
          emailToClient: boolean;
          emailOverride: string | null;
        };
        const { processGdprExportJob } = await import('@/lib/services/gdpr-export.service');
        await processGdprExportJob(data);
        break;
      }
      default:
        logger.warn({ jobName: job.name }, 'Unknown export job');
    }
  },
  {
    connection: { url: env.REDIS_URL } as ConnectionOptions,
    concurrency: QUEUE_CONFIGS.export.concurrency,
  },
);

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

attachWorkerAudit(exportWorker, 'export');
