import { Injectable } from '@nestjs/common';
import { FIREBASE_CREDS } from 'config/firebase.config';
const admin = require('firebase-admin');

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

@Injectable()
export class SendFirebaseNotifications {
  async sendToDevice(
    title: string,
    body: string,
    devices_tokens: Array<string>,
    data:any,
  ) {
    try {
      console.log('devices tokens for notifications', devices_tokens);
      if (devices_tokens.length > 0) {
        devices_tokens.forEach(async (device_token) => {
          if (device_token !== '') {
            const message = {
              notification: {
                body,
                title,
              },
              data,
              token: device_token,
            };
            await admin
              .messaging()
              .send(message)
              .then((response) => {
                console.log('Successfully sent message:', response);
              })
              .catch(async (error) => {
                console.log('Error sending message:', error.message);
              });
          }
        });
      }
    } catch (err) {
      console.log('err', err);
    }
  }
}
