const prisma = require("../lib/prisma");

/**
 * Notify a single user (DB + real-time)
 * @param {object} req - express request (used to access io)
 * @param {number} userId - target user id
 * @param {string} message - notification message
 */
exports.notifyUser = async (req, userId, message, senderId) => {
  const notification = await prisma.notification.create({
    data: {
      userId,
      message,
      senderId,
    },
    include: { sender: { select: { id: true, firstName: true, lastName: true } } },
  });

  const io = req.app.get("io");
  if (io) {
    io.to(`user_${userId}`).emit("new-notification", notification);
  }

  return notification;
};

/**
 * Notify multiple users (DB + real-time)
 * @param {object} req
 * @param {number[]} userIds
 * @param {string} message
 */
exports.notifyManyUsers = async (req, userIds, message, senderId) => {
  if (!userIds || userIds.length === 0) return;

  // Save notifications in DB
  await prisma.notification.createMany({
    data: userIds.map((id) => ({ userId: id, message, senderId })),
  });

  // Fetch sender info
  let sender = null;
  if (senderId) {
    sender = await prisma.user.findUnique({
      where: { id: senderId },
      select: { id: true, firstName: true, lastName: true },
    });
  }

  // Emit real-time event to each user
  const io = req.app.get("io");
  if (io) {
    userIds.forEach((id) => {
      io.to(`user_${id}`).emit("new-notification", {
        id: Math.random(), // temporary ID if needed
        message,
        userId: id,
        isRead: false,
        createdAt: new Date(),
        sender, // include sender object
      });
    });
  }
};

