import authModel from "../DB/Model/user.model.js";
import NotificationModel from "../DB/Model/notification.model.js";
import CustomError from "../Utils/ResponseHandler/CustomError.js";
import CustomSuccess from "../Utils/ResponseHandler/CustomSuccess.js";
import mongoose from "mongoose";
import pushNotifications from "../Config/push_notification.js";

const fetchNotificationsByUserId = async (req, res, next) => {
  try {
    const userId = new mongoose.Types.ObjectId(req.user._id);

    // Fetch total notification count
    const totalCount = await NotificationModel.countDocuments({ user: userId });

    // Fetch paginated notifications
    const notifications = await NotificationModel.find().sort({ createdAt: -1 });
    // Count unread notifications
    const unreadCount = await NotificationModel.countDocuments({ user: userId, isRead: false });
    return res.status(200).json({
      success: true,
      data: notifications,
      unreadCount, // Total unread notifications count
    });
  } catch (err) {
    return next(err);
  }
};

const createNotification = async (req, res, next) => {
  // try {
  const { type, title, messages, link, tokens } = req.body;
  console.log("Creating notification...", req.body);
  const notification = new NotificationModel({
    type,
    title,
    messages,
    link,
    tokens,
    user: req.user._id
  });
  await pushNotifications(type, title, messages, link, notification.user);
  console.log(type, title, messages, link, tokens, "pushNotifications- data");
  // Save the notification to the database
  const createdNotification = await notification.save();

  console.log(createNotification);

  return res.status(201).json({
    success: true,
    data: createdNotification,
  });
};

const deleteNotificationsByUserId = async (req, res, next) => {
  try {
    const userId = req.params.id;

    // Delete notifications based on user ID
    const deletedNotifications = await NotificationModel.deleteMany({
      user: userId,
    });

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

const notificationToggle = async (req, res, next) => {
  try {
    const userId = req.user._id;
    const { notificationToggle, deviceToken } = req.body;

    const notification = await authModel
      .findByIdAndUpdate(
        userId,
        {
          notificationOn: !notificationToggle,
        },
        {
          new: true,
        },
      )
      .select("notificationOn");
    return res.status(200).json({
      success: true,
      message: "Notification toggled successfully",
      data: {
        notification: notification,
      },
    });
  } catch (error) {
    return next(error);
  }
};

const updateStatus = async (req, res, next) => {
  try {
    const notification_id = req.params.id;

    if (!notification_id) {
      return res.status(400).json({ status: false, message: 'Notification ID is required' });
    }

    const updatedNotification = await NotificationModel.findByIdAndUpdate(
      notification_id,
      { isRead: true },
      { new: true }
    );

    if (!updatedNotification) {
      return res.status(404).json({ status: false, message: 'Notification not found' });
    }


    return res.status(200).json({ status: true, message: 'Notification marked as read', data: updatedNotification });
  } catch (error) {
    return next(error);
  }
};

const deleteNotification = async (req, res, next) => {
  try {
    const id = req.params.id;

    const result = await NotificationModel.findOneAndDelete({ _id: id }, { new: true });

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

    return res.status(200).json({
      success: true,
      message: "Notification deleted successfully",
    });
  } catch (err) {
    return next(err);
  }
};

const markAllAsRead = async (req, res, next) => {
  try {
    const userId = req.user._id;

    // Mark all notifications as read for the user
    await NotificationModel.updateMany(
      { user: userId, isRead: false },
      { isRead: true }
    );

    return res.status(200).json({
      success: true,
      message: "All notifications marked as read",
    });
  } catch (error) {
    return next(error);
  }
};

const NotificationController = {
  createNotification,
  fetchNotificationsByUserId,
  deleteNotificationsByUserId,
  notificationToggle,
  updateStatus,
  deleteNotification,
  markAllAsRead
};

export default NotificationController;