import { Injectable, Logger } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { AdminRepository } from 'src/modules/admin/repositories/admin.repository';
import { PagerCreatedEvent } from '../events/pager.events';
import { Permission } from 'src/common/enums/permission.enum';
import { NotifTitleEnum } from 'src/modules/notifications/interfaces/notification.interface';
import { NotificationService } from 'src/modules/notifications/services/notification.service';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class PagerListeners {
  private readonly logger = new Logger(PagerListeners.name);
  private readonly smsPatternPagerCreated: string
  constructor(
    private readonly adminService: AdminRepository,
    private readonly notificationService: NotificationService,
    private readonly configService: ConfigService,
  ) {
    this.smsPatternPagerCreated = this.configService.get<string>('SMS_PATTERN_PAGER_CREATED') ?? '123';
  }

  @OnEvent(PagerCreatedEvent.name)
  async handlePagerCreated(event: PagerCreatedEvent) {
    try {
      this.logger.log(`Pager created event received: ${event.restaurantId}`);
      // get admnin os restuaraant that have pager permissuins
      const admins = await this.adminService.findAdminsWithPermission(event.restaurantId, Permission.PAGER_NOTIFICATION);
      const recipients = admins.map(admin => ({
        adminId: admin.id,
      }));
      await this.notificationService.sendNotification({
        restaurantId: event.restaurantId,
        message: {
          title: NotifTitleEnum.PAGER_CREATED,
          content: `میز شماره ${event.tableNumber} پیج جدیدی انجام داد`,
          sms: {
            templateId: this.smsPatternPagerCreated,
            parameters: {
              tableNumber: event.tableNumber.toString(),
            },
          },
          pushNotif: {
            title: ` پیج جدید`,
            content: `میز شماره ${event.tableNumber} پیج جدیدی انجام داد`,
            icon: `/assets/images/logo.png`,
            action: {
              type: NotifTitleEnum.PAGER_CREATED,
              url: `/restaurants/${event.restaurantId}/pagers`,
            },
          },
        },
        recipients,
        metadata: {
          priority: 1,
        },
      });
    } catch (error) {
      this.logger.error(
        `Failed to send notification for pager created event: ${event.restaurantId}`,
        error instanceof Error ? error.stack : String(error),
      );
    }
  }
}
