const SellerNotifications = require("../../models/SellerNotifications");
const moment = require("moment");
const { Op } = require("sequelize");

exports.getAllNotificationsPaginate = async (req, res, next) => {
  try {
    const { seller_id } = req;
    const { page = 1, limit = 10 } = req.query;

    const offset = (parseInt(page) - 1) * parseInt(limit);

    if (!seller_id) {
      return res.status(200).json({
        success: false,
        message: "Missing seller_id.",
      });
    }

    const { count, rows } = await SellerNotifications.findAndCountAll({
      where: { seller_company_id: seller_id },
      order: [["id", "DESC"]],
      offset,
      limit: parseInt(limit),
    });

    const grouped = {};

    rows.forEach((notif) => {
      const createdAt = moment(notif.createdAt);
      let groupLabel;

      if (createdAt.isSame(moment(), "day")) {
        groupLabel = "Today";
      } else if (createdAt.isSame(moment().subtract(1, "day"), "day")) {
        groupLabel = "Yesterday";
      } else {
        groupLabel = createdAt.format("YYYY-MM-DD");
      }

      if (!grouped[groupLabel]) {
        grouped[groupLabel] = [];
      }

      grouped[groupLabel].push(notif);
    });

    return res.status(200).json({
      success: true,
      currentPage: parseInt(page),
      totalPages: Math.ceil(count / limit),
      totalItems: count,
      groupedNotifications: grouped,
    });
  } catch (err) {
    next(err);
  }
};
exports.markNotificationAsRead = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { seller_id } = req;

    if (!id) {
      return res.status(200).json({
        success: false,
        message: "Notification ID is required.",
      });
    }

    const notification = await SellerNotifications.findOne({
      where: {
        id,
        seller_company_id: seller_id,
      },
    });

    if (!notification) {
      return res.status(200).json({
        success: false,
        message: "Notification not found.",
      });
    }

    if (!notification.is_read) {
      notification.is_read = true;
      await notification.save();
    }

    return res.status(200).json({
      success: true,
      message: "Notification marked as read.",
      data: notification,
    });
  } catch (err) {
    next(err);
  }
};
exports.getUnreadNotifications = async (req, res, next) => {
  try {
    const { seller_id } = req;

    if (!seller_id) {
      return res.status(200).json({
        success: false,
        message: "Missing seller_id.",
      });
    }

    const count = await SellerNotifications.count({
      where: {
        seller_company_id: seller_id,
        is_read: false,
      },
    });

    return res.status(200).json({
      success: true,
      count,
    });
  } catch (err) {
    next(err);
  }
};
