const { Op } = require('sequelize');
const { Conversations, ConversationMembers, Sequelize, Messages } = require('../models');

const getLatestMessage = async (customerId, hostId) => {
  try {
    // both the customer and host are members
    const conversation = await Conversations.findOne({
      include: [
        {
          model: ConversationMembers,
          as: 'members',
          where: { user_id: { [Op.in]: [customerId, hostId] } },
          required: true,
        },
      ],
    });

    if (!conversation) {
      return null;
    }

    // find the latest message **only from the customer**
    const lastMessage = await Messages.findOne({
      where: {
        convo_id: conversation.id,
        sender_id: customerId,
      },
      order: [['createdAt', 'DESC']],
      attributes: ['id', 'sender_id', 'content', 'is_seen', 'createdAt'],
    });

    if (!lastMessage) {
      return null;
    }

    return {
      content: lastMessage.content,
      isSeen: lastMessage.is_seen,
    };
  } catch (error) {
    return null;
  }
};

module.exports = getLatestMessage;
