const jwt = require("jsonwebtoken");
const PushNotifications = require("../models/pushNotificationsModel");
const User = require("../models/userModel");
const moment = require("moment/moment");

const verification = async (token) => {
  try {
    // if (token.startsWith("Bearer ")) {
    //   TokenArray = token.split(" ");
    //   const decoded = jwt.verify(TokenArray[1], process.env.JWT_SECRET);
    //   const user = await User.findOne({ _id: decoded.id });
    //   if (user !== null && decoded.exp > Date.now() / 1000) {
    //     return true;
    //   } else {
    //     return false;
    //   }
    // } else {
    //   return false;
    // }
    return true;
  } catch (error) {
    return false;
  }
};

exports.getPushNotifications = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const pushNotification = await PushNotifications.find({ IsDelete: false });
    res.setHeader("Content-Type", "application/json");
    res.status(200).json({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: pushNotification,
    });
  } else {
    res.setHeader("Content-Type", "application/json");
    res.status(401).json({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.getPushNotificationsByUserId = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const userId = req.params.id;
    const pushNotifications = await PushNotifications.find({
      IsDelete: false,
      userId: userId,
    });
    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: pushNotifications,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.savePushNotification = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;

    const allUsers = await User.find({ IsActive: true, IsDelete: false });
    allUsers.map(async (user) => {
      const data = {
        date: body.date,
        message: body.message,
        isRead: false,
        userId: user._id,
        IsActive: body.IsActive,
        IsDelete: false,
        CreatedBy: body.User,
        CreatedOn: moment().format("YYYY-MMM-DD"),
      };
      const newPushNotification = await PushNotifications.create(data);
    });
    // const data = {
    //   date: body.date,
    //   message: body.message,
    //   isRead: false,
    //   userId: body.userId,
    //   IsActive: body.IsActive,
    //   IsDelete: false,
    //   CreatedBy: body.User,
    //   CreatedOn: moment().format("YYYY-MMM-DD"),
    // };
    // const newPushNotification = await PushNotifications.create(data);
    res.json({
      message: "New PushNotification created successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: {
        date: body.date,
        message: body.message,
        isRead: false,
        userId: null,
        IsActive: body.IsActive,
        IsDelete: false,
        CreatedBy: body.User,
        CreatedOn: moment().format("YYYY-MMM-DD"),
      },
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.editPushNotification = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updatePushNotification = await PushNotifications.updateOne(
      { _id: body._id },
      {
        $set: {
          date: body.date,
          message: body.message,
          isRead: false,
          userId: body.userId,
          IsActive: body.IsActive,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MMM-DD"),
        },
      }
    );
    const updatedPushNotification = await PushNotifications.findById(body._id);
    res.json({
      message: "PushNotification updated successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedPushNotification,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.markAsRead = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const notificationID = req.params.id;
    const updatePushNotification = await PushNotifications.updateOne(
      { _id: notificationID },
      {
        $set: {
          isRead: true,
        },
      }
    );
    const updatedPushNotification = await PushNotifications.findById(
      notificationID
    );
    res.json({
      message: "PushNotification marked as read successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedPushNotification,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.deletePushNotification = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;
    const updatePushNotification = await PushNotifications.updateOne(
      { _id: body._id },
      {
        $set: {
          IsActive: body.IsActive,
          IsDelete: body.IsDelete,
          ModifiedBy: body.User,
          ModifiedOn: moment().format("YYYY-MMM-DD"),
        },
      }
    );
    const updatedPushNotification = await PushNotifications.findOne({
      _id: body._id,
    });
    res.json({
      message: "PushNotification deleted successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: updatedPushNotification,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};
