import { Processor, WorkerHost, OnWorkerEvent } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityManager } from '@mikro-orm/postgresql';
import { Notification } from '../entities/notification.entity';
import { InAppNotificationQueueJob } from '../interfaces/jobs-queue.interface';
import { NotificationQueueNameEnum } from '../constants/queue';
import { NotificationsGateway } from '../notifications.gateway';

@Processor(NotificationQueueNameEnum.IN_APP)
export class InAppProcessor extends WorkerHost {
  private readonly logger = new Logger(InAppProcessor.name);

  constructor(
    @InjectRepository(Notification)
    private readonly em: EntityManager,
    private readonly notificationsGateway: NotificationsGateway,
  ) {
    super();
  }

  async process(job: Job<InAppNotificationQueueJob>): Promise<void> {
    const { recipient, subject, body, notificationId } = job.data;

    this.logger.log(`Processing InApp notification - Recipient: ${JSON.stringify(recipient)}, subject: ${subject}`);

    try {
      this.notificationsGateway.sendInAppNotification(
        { adminId: recipient.adminId, restaurantId: recipient.restaurantId },
        { subject, body, notificationId },
      );

      this.logger.log(`InApp notification sent successfully to ${recipient.adminId}`);
    } catch (error) {
      this.logger.error(`Error processing InApp notification job ${job.id}:`, error);
      throw error;
    }
  }

  @OnWorkerEvent('completed')
  onCompleted(job: Job) {
    this.logger.log(`Notification job ${job.id} completed`);
  }

  @OnWorkerEvent('failed')
  onFailed(job: Job, error: Error) {
    this.logger.error(`Notification job ${job.id} failed:`, error);
  }
}
