const ConversationsLogistics = require('../models/ConversationsLogistics');
const ChatsLogistics = require('../models/ChatsLogistics');
const Customers = require('../models/Customers');
const Logistics = require('../models/Logistics');

exports.sendMessageForBuyer = async (req, res) => {
    try {
        const { message, buyer_id } = req.body;
        const { seller_id } = req.params;
  
        // Check if the buyer_id exists in the Customers model
        const buyerExists = await Customers.findOne({
            where: {
                id: buyer_id
            }
        });
  
        // If buyer_id doesn't exist, return an error
        if (!buyerExists) {
            return res.status(400).json({ message: 'Invalid buyer_id. Buyer does not exist.' });
        }
  
        // Check if the seller_id exists in the Logistics model
        const sellerExists = await Logistics.findOne({
            where: {
                id: seller_id
            }
        });
  
        // If seller_id doesn't exist, return an error
        if (!sellerExists) {
            return res.status(400).json({ message: 'Invalid seller_id. Seller does not exist.' });
        }
  
        // Check if there's an existing conversation between the seller and buyer
        let conversation = await ConversationsLogistics.findOne({
            where: {
                buyer_id,
                seller_id
            }
        });
  
        // If no existing conversation found, create a new one
        if (!conversation) {
            conversation = await ConversationsLogistics.create({ buyer_id, seller_id });
        }
  
        const conversation_id = conversation.id;
  
        let isSeen_buyer = 0;
        let isSeen_seller = 1; // Set isSeen_seller to 1 since the message is being sent by the seller
  
        // Get the current date in UTC
        const currentDateUTC = new Date();
  
        // Convert UTC to Singapore time (UTC +8:00)
        const singaporeTime = new Date(currentDateUTC.getTime() + (8 * 60 * 60 * 1000));
  
        const chat = await ChatsLogistics.create({ 
            conversation_id, 
            seller_id, 
            message, 
            isSeen_buyer, 
            isSeen_seller, 
            created_on: singaporeTime // Use Singapore time for created_on field
        });
        
        // Update the last_updated field in the ConversationsLogistics model with Singapore time
        await conversation.update({ last_updated: singaporeTime });
  
        res.status(201).json(chat);
    } catch (error) {
        console.error(error);
        return res.status(500).json({ message: 'Server Error' });
    }
  };
  

exports.sendMessageForSeller = async (req, res) => {
  try {
      const { message, seller_id } = req.body; // Extract seller_id from req.body
      const { buyer_id } = req.params; // Extract buyer_id from req.params

      // Check if the buyer_id exists in the Customers model
      const buyerExists = await Customers.findOne({
          where: {
              id: buyer_id
          }
      });

      // If buyer_id doesn't exist, return an error
      if (!buyerExists) {
          return res.status(400).json({ message: 'Invalid buyer_id. Buyer does not exist.' });
      }

      // Check if the seller_id exists in the Logistics model
      const sellerExists = await Logistics.findOne({
          where: {
              id: seller_id
          }
      });

      // If seller_id doesn't exist, return an error
      if (!sellerExists) {
          return res.status(400).json({ message: 'Invalid seller_id. Seller does not exist.' });
      }

      // Check if there's an existing conversation between the seller and buyer
      let conversation = await ConversationsLogistics.findOne({
          where: {
              buyer_id,
              seller_id
          }
      });

      // If no existing conversation found, create a new one
      if (!conversation) {
          conversation = await ConversationsLogistics.create({ buyer_id, seller_id });
      }

      const conversation_id = conversation.id;

      let isSeen_buyer = 1;
      let isSeen_seller = 0; // Set isSeen_seller to 1 since the message is being sent by the seller

      // Get the current date in UTC
      const currentDateUTC = new Date();

      // Convert UTC to Singapore time (UTC +8:00)
      const singaporeTime = new Date(currentDateUTC.getTime() + (8 * 60 * 60 * 1000));

      const chat = await ChatsLogistics.create({ 
          conversation_id, 
          buyer_id, 
          message, 
          isSeen_buyer, 
          isSeen_seller, 
          created_on: singaporeTime // Use Singapore time for created_on field
      });
      
      // Update the last_updated field in the ConversationsLogistics model with Singapore time
      await conversation.update({ last_updated: singaporeTime });

      res.status(201).json(chat);
  } catch (error) {
      console.error(error);
      return res.status(500).json({ message: 'Server Error' });
  }
};

exports.deleteChat = async (req, res) => {
    try {
        const { chatId } = req.params;

        // Find the chat by ID
        const chat = await ChatsLogistics.findByPk(chatId);

        // If chat doesn't exist, return an error
        if (!chat) {
            return res.status(404).json({ message: 'Chat not found' });
        }

        // Update the chat to mark it as deleted
        await chat.update({ isDeleted: "True" });

        // Return the updated chat along with success message
        res.json({ success: 'Deleted successfully' });
    } catch (error) {
        console.error(error);
        return res.status(500).json({ message: 'Server Error' });
    }
};



