const Notification = require("../models/notificationModel");
const User = require("../models/userModel")
const { sendPushNotification } = require("./pushNotification.service");


async function createNotification({
    userId,
    orgId,
    title,
    message,
    type,
    metadata = {},
}) {
    const notification = await Notification.create({
        userId,
        orgId,
        title,
        message,
        type,
        metadata,
    });

    const user = await User.findById(userId).select("deviceToken");

    // Send push notification
    if (user?.deviceToken) {
        await sendPushNotification({
            token: user.deviceToken,
            title,
            body: message,
            data: {
                type,
                notificationId: notification._id.toString(),
            },
        });
    }

    //  FUTURE (not now)
    // sendPushNotification(...)
    // emitSocketEvent(...)

    return notification;
}

module.exports = {
    createNotification,
};
