import { InjectQueue } from '@nestjs/bullmq';
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { Queue } from 'bullmq';
import EventBus from '@server/utils/event-bus';
import { ObjectType, VisitType } from '@nice/common';
import {
  QueueJobType,
  updatePostStateJobData,
  updateVisitCountJobData,
} from '@server/queue/types';

@Injectable()
export class PostQueueService implements OnModuleInit {
  private readonly logger = new Logger(PostQueueService.name);
  constructor(@InjectQueue('general') private generalQueue: Queue) {}
  onModuleInit() {
    EventBus.on('updateVisitCount', ({ id, objectType, visitType }) => {
      if (objectType === ObjectType.POST) {
        this.addUpdateVisitCountJob({ id, type: visitType });
      }
    });
    EventBus.on('updatePostState', ({ id }) => {
      this.addUpdatePostState({ id });
    });
  }
  async addUpdateVisitCountJob(data: updateVisitCountJobData) {
    this.logger.log(`update post view count ${data.id}`);
    await this.generalQueue.add(QueueJobType.UPDATE_POST_VISIT_COUNT, data, {
      debounce: {
        id: `${QueueJobType.UPDATE_POST_VISIT_COUNT}_${data.type}_${data.id}`,
      },
    });
  }
  async addUpdatePostState(data: updatePostStateJobData) {
    this.logger.log(`update post state ${data.id}`);
    await this.generalQueue.add(QueueJobType.UPDATE_POST_STATE, data, {
      debounce: { id: `${QueueJobType.UPDATE_POST_STATE}_${data.id}` },
    });
  }
}
