const Message = require('../models/Message'); const getChatHistory = async (req, res) => { try { const { otherUserId } = req.params; const currentUserId = req.user._id; const messages = await Message.find({ $or: [ { sender: currentUserId, receiver: otherUserId }, { sender: otherUserId, receiver: currentUserId } ] }).sort({ createdAt: 1 }); res.json(messages); } catch (error) { res.status(500).json({ message: error.message }); } }; const getRecentConversations = async (req, res) => { try { const currentUserId = req.user._id; // Find recent messages where user is sender or receiver const recentMessages = await Message.find({ $or: [{ sender: currentUserId }, { receiver: currentUserId }] }) .sort({ createdAt: -1 }) .populate('sender', 'firstName lastName profilePicture') .populate('receiver', 'firstName lastName profilePicture'); // Extract unique users const conversations = []; const seenUsers = new Set(); recentMessages.forEach(msg => { try { // Ensure participants are correctly populated if (!msg.sender || !msg.receiver || !msg.sender._id || !msg.receiver._id) return; const otherUser = msg.sender._id.toString() === currentUserId.toString() ? msg.receiver : msg.sender; // Ensure otherUser is fully populated (has at least firstName) if (!otherUser || !otherUser.firstName) return; if (!seenUsers.has(otherUser._id.toString())) { seenUsers.add(otherUser._id.toString()); conversations.push({ user: otherUser, lastMessage: msg.content, timestamp: msg.createdAt }); } } catch (err) { console.error('Error processing conversation:', err); // Continue to next message } }); res.json(conversations); } catch (error) { console.error('getRecentConversations 500 Error:', error); res.status(500).json({ message: error.message }); } }; module.exports = { getChatHistory, getRecentConversations };