import { Injectable, Logger } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { ReviewCreatedEvent } from '../events/review.events';
import { AdminRepository } from 'src/modules/admin/repositories/admin.repository';
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 ReviewListeners {
    private readonly logger = new Logger(ReviewListeners.name);
    private reviewCreatedSmsTemplateId: string;

    constructor(
        private readonly adminService: AdminRepository,
        private readonly notificationService: NotificationService,
        private readonly configService: ConfigService,
    ) {
        this.reviewCreatedSmsTemplateId = this.configService.get<string>('SMS_PATTERN_REVIEW_CREATED') ?? '123';
    }

    @OnEvent(ReviewCreatedEvent.name)
    async handleReviewCreated(event: ReviewCreatedEvent) {
        try {
            this.logger.log(
                `Review created event received: ${event.reviewId} for restaurant: ${event.restaurantId}, food: ${event.foodName}, rating: ${event.rating}`,
            );

            // Get admins of restaurant that have review management permissions
            const admins = await this.adminService.findAdminsWithPermission(event.restaurantId, Permission.MANAGE_REVIEWS);
            const recipients = admins.map(admin => ({
                adminId: admin.id,
            }));

            if (recipients.length === 0) {
                this.logger.warn(`No admins found with MANAGE_REVIEWS permission for restaurant ${event.restaurantId}`);
                return;
            }

            await this.notificationService.sendNotification({
                restaurantId: event.restaurantId,
                message: {
                    title: NotifTitleEnum.REVIEW_CREATED,
                    content: `نظر جدید برای غذا "${event.foodName}" با امتیاز ${event.rating} از 5 برای سفارش شماره ${event.orderNumber} ثبت شد`,
                    sms: {
                        templateId: this.reviewCreatedSmsTemplateId,
                        parameters: {
                            foodName: event.foodName,
                            rating: event.rating.toString(),
                            orderNumber: String(event.orderNumber),
                        },
                    },
                    pushNotif: {
                        title: `نظر جدید`,
                        content: `نظر جدید برای غذا "${event.foodName}" با امتیاز ${event.rating} ثبت شد`,
                        icon: `/`,
                        action: {
                            type: NotifTitleEnum.REVIEW_CREATED,
                            url: `/`,
                        },
                    },
                },
                recipients,
                metadata: {
                    priority: 1,
                },
            });
        } catch (error) {
            this.logger.error(
                `Failed to send notification for review created event: ${event.reviewId}`,
                error instanceof Error ? error.stack : String(error),
            );
        }
    }
}

