import { Inject, Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import type { Job as BullJob, Worker } from 'bullmq';
import { JobsService } from '../jobs/jobs.service';
import { RedisQueueService } from '../jobs/redis-queue.service';
import { CampaignsService } from './campaigns.service';

@Injectable()
export class CampaignWorkerService implements OnModuleInit, OnModuleDestroy {
  private worker: Worker | null = null;

  constructor(
    private readonly jobsService: JobsService,
    @Inject(RedisQueueService)
    private readonly redisQueueService: RedisQueueService,
    private readonly campaignsService: CampaignsService,
  ) {}

  onModuleInit() {
    this.worker = this.redisQueueService.createWorker(
      'campaigns',
      async (job: BullJob<{ dbJobId?: string }>) => {
        const dbJobId = job.data?.dbJobId;
        if (!dbJobId) {
          throw new Error('Redis campaign job missing dbJobId');
        }

        const claimed = await this.jobsService.markProcessing(dbJobId);
        if (!claimed) {
          return;
        }

        await this.campaignsService.processJob(dbJobId);
      },
    );
  }

  async onModuleDestroy() {
    if (this.worker) {
      await this.worker.close();
      this.worker = null;
    }
  }
}
