import { Injectable } from '@nestjs/common';
import { CreateNotificationDto } from './dto/create-notification.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Notification } from './entities/notification.entity';
import { IsNull, Not, Repository } from 'typeorm';
import { NotificationRepository } from './notifications.repository';
import { AppUser } from 'src/app_users/entities/app_user.entity';
import { SendNotificationService } from 'src/common/push-notification';
import * as admin from 'firebase-admin';
require('dotenv').config();

const serviceAccount = {
  projectId: process.env.PROJECT_ID,
  clientEmail: process.env.CLIENT_EMAIL,
  privateKey: process.env.PRIVATE_KEY.replace(/\\n/g, '\n'),
};

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

@Injectable()
export class NotificationsService {
  constructor(
    @InjectRepository(Notification)
    private readonly notificationEntity: Repository<Notification>,
    private readonly notificationRepository: NotificationRepository,
    @InjectRepository(AppUser)
    private readonly appUserRepository: Repository<AppUser>,
    private readonly sendNotificationService: SendNotificationService,
  ) {}

  async create(createNotificationDto: CreateNotificationDto) {
    const notification = new Notification();
    Object.assign(notification, createNotificationDto);

    await this.notificationEntity.save(notification);

    const usersWithFcmTokens = await this.appUserRepository.find({
      where: { fcm_token: Not(IsNull()), notify: true },
      select: ['fcm_token', 'id'],
    });

    const fcmTokens = usersWithFcmTokens.map((user) => user.fcm_token);

    if (fcmTokens.length > 0) {
      for (const user of usersWithFcmTokens) {
        const fcmToken = user.fcm_token;
        const extraData = {
          user_id: user.id.toString(),
        };

        await this.sendNotificationService.send(
          [fcmToken],
          createNotificationDto.title,
          createNotificationDto.content,
          extraData,
        );
      }
    }
  }

  async findAll(take: number, skip: number) {
    return this.notificationRepository.findAllNotification(take, skip);
  }

  async findUserNotification(userId: string, take: number, skip: number) {
    return this.notificationRepository.findUserNotification(userId, take, skip);
  }
}
