const prisma = require("../lib/prisma");
const { notifyUser } = require("../services/notification.service");

// =======================
// GET my notifications
// =======================
exports.getMyNotifications = async (req, res) => {
  try {
    // Get query params
    const page = parseInt(req.query.page) || 0; // current page, 0-indexed
    const pageSize = parseInt(req.query.pageSize) || 10; // items per page

    // Fetch notifications and total count
    const [rows, count] = await prisma.$transaction([
      prisma.notification.findMany({
        where: { userId: req.user.id },
        orderBy: { createdAt: "desc" },
        include: {
          sender: {
            select: {
              id: true,
              firstName: true,
              lastName: true,
            },
          },
        },
        skip: page * pageSize, // skip previous pages
        take: pageSize, // take current page
      }),
      prisma.notification.count({
        where: { userId: req.user.id }, // total count for the user
      }),
    ]);

    res.json({ rows, count }); // return both
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Failed to fetch notifications" });
  }
};

// =======================
// SEND notification (admin / teacher / accountant)
// =======================
exports.sendNotification = async (req, res) => {
  const senderId = req.user.id;
  const { targetUserId, message } = req.body;

  // 🔔 DB + Real-time notification
  await notifyUser(req, targetUserId, message, senderId);

  res.json({ message: "Notification sent successfully" });
};

// =======================
// MARK AS READ
// =======================
exports.markAsRead = async (req, res) => {
  try {
    const notificationId = parseInt(req.params.id);
    const userId = req.user.id;

    await prisma.notification.updateMany({
      where: {
        id: notificationId,
        userId: userId,
      },
      data: { isRead: true },
    });

    req.io.to(`user_${userId}`).emit("notification-read", {
      notificationId,
    });

    res.json({ message: "Marked as read" });
  } catch (err) {
    console.error("MARK AS READ ERROR", err);
    res.status(500).json({ message: "Failed to mark as read" });
  }
};

exports.sendBulkNotification = async (req, res) => {
  try {
    const senderId = req.user.id;
    const { targetUserIds, role, message } = req.body;

    if (!message) {
      return res.status(400).json({ message: "Message is required" });
    }

    let recipients = [];

    // 1️⃣ If targetUserIds is provided (specific users)
    if (Array.isArray(targetUserIds) && targetUserIds.length > 0) {
      recipients = await prisma.user.findMany({
        where: { id: { in: targetUserIds } },
        select: { id: true },
      });
    }
    // 2️⃣ If role is provided (send to all users of that role)
    else if (role) {
      recipients = await prisma.user.findMany({
        where: { role },
        select: { id: true },
      });
    }
    // 3️⃣ If nothing provided, send to all users
    else {
      recipients = await prisma.user.findMany({
        select: { id: true },
      });
    }

    if (recipients.length === 0) {
      return res.status(404).json({ message: "No recipients found" });
    }

    // 🔔 Loop through recipients and notify
    const notifications = [];
    for (const user of recipients) {
      const notif = await notifyUser(req, user.id, message, senderId);
      notifications.push(notif);
    }

    res.json({
      message: `Notification sent to ${recipients.length} user(s)`,
      notifications,
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Server error" });
  }
};

exports.getNotificationsById = async (req, res) => {
  const { id } = req.params;

  try {
    // Find the notification by ID
    const notification = await prisma.notification.findUnique({
      where: { id: parseInt(id) },
      include: {
        sender: true, // include sender info if you have a relation
      },
    });

    if (!notification) {
      return res.status(404).json({ message: "Notification not found" });
    }

    // Send normalized response
    res.json({
      id: notification.id,
      title: notification.message,
      date: notification.date,
      isRead: notification.isRead,
      sender: notification.sender
        ? {
            firstName: notification.sender.firstName,
            lastName: notification.sender.lastName,
          }
        : null,
    });
  } catch (err) {
    console.error("Error fetching notification:", err);
    res.status(500).json({ message: "Server error" });
  }
};