const axios = require("axios");
const { splitSite } = require("../middlewares");
const db = require("../models");
const Message = db.message;
const MessageToken = db.message_token;
const SentMessage = db.sent_message;

exports.createMessage = (req, res) => {
  const site = splitSite.findSiteNumber(req);
  const message = new Message({
    // Legacy fields
    message_group: req.body.message_group,
    message_name: req.body.message_name,
    message_title: req.body.message_title,
    message_body: req.body.message_body,
    // New fields
    title: req.body.title,
    language: req.body.language,
    sent_date: req.body.sent_date,
    message: req.body.message,
    recipient_name: req.body.recipient_name,
    recipient_id: req.body.recipient_id,
    create_by: req.body.create_by,
    create_date: req.body.create_date,
    site
  });

  message
    .save(message)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Message."
      });
    });
};

// Bulk create messages
exports.createMessages = (req, res) => {
  const site = splitSite.findSiteNumber(req);
  const entries = req.body.entries || [];
  if (!entries.length) {
    return res.status(400).send({ message: "No messages to create." });
  }
  const docs = entries.map(entry => ({
    title: entry.title,
    language: entry.language,
    sent_date: entry.sent_date,
    message: entry.message,
    recipient_name: entry.recipient_name,
    recipient_id: entry.recipient_id,
    create_by: entry.create_by,
    create_date: entry.create_date,
    site
  }));
  Message.insertMany(docs)
    .then(data => {
      res.send({ success: true, data });
    })
    .catch(err => {
      res.status(500).send({
        message: err.message || "Some error occurred while creating messages."
      });
    });
};
// Retrieve all Messages from the database.
exports.getAllMessages = (req, res) => {
  var condition = {};
  Message.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving messages."
      });
    });
};

// Retrieve messages By group and language 
exports.getMessagesByGroupAndLanguage= (req, res) => {
  const params = req.query;
  const message_group = params?.message_group;
  const language = params?.language;
  var condition = { message_group, language };
  Message.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving Messages with Date and Type."
      });
    });
};

// Get One Message by Id
exports.getMessage = (req, res) => {
  const id = req.params.id;
  Message.findById(id)
    .then(data => {
      if (!data)
        res.status(404).send({ message: "Not found Message with id " + id });
      else res.send(data);
    })
    .catch(err => {
      res
        .status(500)
        .send({ message: "Error retrieving Message with id=" + id });
    });
};
// Update a Message by the id in the request
exports.updateMessage = (req, res) => {
  if (!req.body) {
    return res.status(400).send({
      message: "Data to update can not be empty!"
    });
  }
  const id = req.params.id;
  Message.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
    .then(data => {
      if (!data) {
        res.status(404).send({
          message: `Cannot update Message with id=${id}. Maybe Message was not found!`
        });
      } else res.send({ success: true, message: "Message was updated successfully." });
    })
    .catch(err => {
      res.status(500).send({
        success: false,
        message: "Error updating Message with id=" + id
      });
    });
};


// exports.sendMessage = async (req, res) => {
//   console.log(req.body);
//   if (!req.body) {
//     return res.status(400).send({
//       message: "Data to update can not be empty!"
//     });
//   }
//   const authToken = await MessageToken.find({});
//   if (authToken && authToken.length > 0) {
//     const token = authToken[0]?.message_token;
//     console.log('token', token);
//     await axios.post('https://api-app2.simpletexting.com/v2/api/messages', req.body, {
//       headers: { 
//         "Authorization": `Bearer ${token}`,
//         "Content-Type": "application/json",
//       },
//     }).then(() => {
//       res.send({success: true, message: "Message Sent Correctly"})
//     }).catch(err => console.log(err));
//   }
// }

// Retrieve all Sent Messages from the database.
exports.getAllSentMessages = (req, res) => {
  var condition = {};
  condition = splitSite.splitSiteGet(req, condition);
  SentMessage.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving sent messages."
      });
    });
};

exports.sendMessage = async (req, res) => {
  if (!req.body) {
    return res.status(400).send({
      message: "Data to update can not be empty!"
    });
  }
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  const messages = req.body.messages;
  
  for(const message of messages) {
    try {
      await axios.post('https://rest.textmagic.com/api/v2/messages', {
        text: message?.text,
        phones: message?.contactPhone
      }, {
        headers: {
          "X-TM-Username": "oauthyhma",
          "X-TM-Key": "Rin866o0cMMAJXkCiIyYd2pw9HSeGo" 
        }
      })
      const site = splitSite.findSiteNumber(req);
      const sentMessage = new SentMessage({
        from_type: 'center',
        from: message.from || 'center',
        to_type: 'client',
        to: message.contactPhone || '',
        department: message.department || '',
        content: message.text || '',
        status: 'active',
        create_by: 'admin',
        create_date: new Date(),
        site
      });
      await sentMessage.save(sentMessage);
      await sleep(200);
    } catch (err) {
      console.log(err);
    } 
    
  }
  res.send({success: true, message: "Message Sent Correctly"});
}

