const messageModel = require("../models/messageModel");
const { addMessgeAuth } = require("../authentication/messageAuth");
const fs = require("fs");
const User = require("../models/user");
const { getById } = require("./user");
// add message

const addMessage = async (req, res) => {
  const { senderId, receiverId, message, date } =
    req.body;

  try {
    await addMessgeAuth(senderId, receiverId,);

    const sender = await User.findOne({ senderId: senderId });

    const receiver = await User.findById( receiverId );

    if (!sender || sender === null) {
     
      res.status(400).json({ error: "sender not found", success: false });

    }else if(!receiver || receiver==null){
      res.status(400).json({ error: "reciever not found", success: false });
    }
    
    else{
      const Message = await messageModel.create({
        senderId,
        receiverId,
        message,
        date,
        sender: sender,
       receiver: receiver,
      });
      res
        .status(200)
        .json({ Message, message: "message sent successfully ", success: true });
      
    }

   
  } catch (error) {
    res.status(404).json({ error: error.message, success: false });
    // console.log(error);
  }
};

//   get all message....................
const getAllMesssage = async (req, res) => {
  try {
    const Message = await messageModel.find().populate("receiver").populate("sender");
    res.status(200).json({ Message, success: true });
  } catch (error) {
    res.status(404).json({ error: error.message, success: false });
  }
};

//   get by ID ......................
const getMessageByID = async (req, res) => {
  try {
    const { senderId, receiverId } = req.body;

    var query = {  
                      $or: [ { senderId: senderId}, { senderId: receiverId } ],
                      $or: [ { receiverId: receiverId}, { receiverId: senderId } ]
  };


    const Message = await messageModel.find(query).populate("receiver").populate("sender").sort({ date: -1 });
    if (!Message) {
      res.status(400).json({ message: "message not found", success: false });
    } else {
      res.status(200).json({ Message, success: true });
    }
  } catch (error) {
    res.status(200).json({ error: error.message, success: false });
  }
};

// Delete message ....................
const deleteMessage = async (req, res) => {
  const { id } = req.params;
  try {
    const Message = await messageModel.findByIdAndDelete(id);
    if (!Message) {
      res.status(400).json({ message: "message not found", success: false });
    } else {
      res.status(200).json({ message: "deleted successfully", success: true });
    }
  } catch (error) {}
};

// update message .......................

const updateMessageByID = async (req, res) => {
  const { id } = req.params;
  const { senderId, senderName, receiverId, receiverName, message } = req.body;
  try {
    const Message = await messageModel.findById(id);
    if (!Message) {
      return res
        .status(400)
        .json({ response: "message not found", success: false });
    }

    const newMessage = {
      senderId,
      senderName,
      receiverId,
      receiverName,
      message,
    };

    const updatedMessage = await messageModel.findByIdAndUpdate(
      id,
      newMessage,
      { new: true }
    );
    return res.status(200).json({
      response: "message updated successfully",
      updatedMessage,
      success: true,
    });
  } catch (error) {}
};

module.exports = {
  getAllMesssage,
  addMessage,
  getMessageByID,
  deleteMessage,
  updateMessageByID,
};
