import { 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 { WebhooksService } from './webhooks.service';

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

  constructor(
    private readonly jobsService: JobsService,
    private readonly redisQueueService: RedisQueueService,
    private readonly webhooksService: WebhooksService,
  ) {}

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

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

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

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