File size: 2,400 Bytes
0f8617c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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 };