import admin from "firebase-admin";
import serviceAccount from "./serviceAccount.js";
import NotificationModel from "../DB/Model/notification.model.js";
import User from "../DB/Model/user.model.js";

// Initialize Firebase Admin SDK (Uncomment this if needed)
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

const push_notification = async (type, title, messages, link, userid) => {

  console.log(type, title, messages, link, userid, "In push_notification");
  const user = await User.findOne({ _id: userid });
  const token = user.fcmToken
  try {

    let message = {
      token: token,
      notification: {
        title: title,
        body: messages,
      },
      data: {
        type: type,
        link: link || "",
      },
    };


    const notification = new NotificationModel({
      type,
      title,
      messages,
      link,
      user: userid
    });
    // Save the notification to the database
    const createdNotifications = await notification.save();
    const response = await admin.messaging().send(message);
    console.log("Successfully sent notification:", response);
  } catch (error) {
    console.error("Error sending notification:", error);
  }
};

export default push_notification;