File size: 8,484 Bytes
057576a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
const Conversation = require('../models/Conversation');
const Message = require('../models/Message');
const User = require('../models/User');
const { generateInviteCode } = require('../utils/helpers');

exports.createConversation = async (req, res) => {
  try {
    const { type, name, description, participantIds } = req.body;
    const userId = req.user.userId;

    // Validate conversation type
    if (!['direct', 'group'].includes(type)) {
      return res.status(400).json({ error: 'Invalid conversation type' });
    }

    // For direct messages, check if conversation already exists
    if (type === 'direct') {
      if (!participantIds || participantIds.length !== 1) {
        return res.status(400).json({ error: 'Direct message requires exactly one participant' });
      }

      const existingConversation = await Conversation.findDirectConversation(userId, participantIds[0]);

      if (existingConversation) {
        await existingConversation.populate('participants.user', 'username displayName avatar status');
        return res.json({ 
          message: 'Conversation already exists',
          conversation: existingConversation 
        });
      }
    }

    // For group conversations, validate name
    if (type === 'group' && (!name || name.trim().length === 0)) {
      return res.status(400).json({ error: 'Group conversation requires a name' });
    }

    // Verify all participants exist
    const participants = await User.find({ 
      _id: { $in: participantIds } 
    }).select('_id');

    if (participants.length !== participantIds.length) {
      return res.status(400).json({ error: 'One or more participants not found' });
    }

    // Create conversation participants array
    const conversationParticipants = [
      { user: userId, role: 'owner' },
      ...participantIds.map(pid => ({ user: pid, role: 'member' }))
    ];

    const conversation = new Conversation({
      type,
      name: type === 'direct' ? null : name.trim(),
      description: type === 'direct' ? null : (description || '').trim(),
      createdBy: userId,
      participants: conversationParticipants
    });

    await conversation.save();
    await conversation.populate('participants.user', 'username displayName avatar status');
    await conversation.populate('createdBy', 'username displayName');

    res.status(201).json({
      message: 'Conversation created successfully',
      conversation
    });
  } catch (error) {
    console.error('❌ Create conversation error:', error);
    res.status(500).json({ error: 'Server error creating conversation' });
  }
};

exports.getUserConversations = async (req, res) => {
  try {
    const userId = req.user.userId;

    const conversations = await Conversation.find({
      'participants.user': userId
    })
    .populate('participants.user', 'username displayName avatar status lastSeen')
    .populate('lastMessage')
    .populate('createdBy', 'username displayName')
    .sort({ updatedAt: -1 });

    res.json({ conversations });
  } catch (error) {
    console.error('❌ Get conversations error:', error);
    res.status(500).json({ error: 'Server error fetching conversations' });
  }
};

exports.getConversation = async (req, res) => {
  try {
    const { conversationId } = req.params;
    const userId = req.user.userId;

    const conversation = await Conversation.findOne({
      _id: conversationId,
      'participants.user': userId
    })
    .populate('participants.user', 'username displayName avatar status lastSeen bio')
    .populate('createdBy', 'username displayName avatar')
    .populate('lastMessage');

    if (!conversation) {
      return res.status(404).json({ error: 'Conversation not found or access denied' });
    }

    res.json({ conversation });
  } catch (error) {
    console.error('❌ Get conversation error:', error);
    res.status(500).json({ error: 'Server error fetching conversation' });
  }
};

exports.getConversationMessages = async (req, res) => {
  try {
    const { conversationId } = req.params;
    const { page = 1, limit = 50 } = req.query;
    const userId = req.user.userId;

    // Check if user is part of conversation
    const conversation = await Conversation.findOne({
      _id: conversationId,
      'participants.user': userId
    });

    if (!conversation) {
      return res.status(404).json({ error: 'Conversation not found or access denied' });
    }

    const pageNum = Math.max(1, parseInt(page));
    const limitNum = Math.min(100, Math.max(1, parseInt(limit))); // Max 100 messages per request

    const messages = await Message.find({ conversation: conversationId })
      .populate('sender', 'username displayName avatar status')
      .populate('replyTo')
      .populate('reactions.user', 'username displayName')
      .sort({ createdAt: -1 })
      .limit(limitNum)
      .skip((pageNum - 1) * limitNum);

    // Reverse to get chronological order (oldest first)
    const sortedMessages = messages.reverse();

    const totalMessages = await Message.countDocuments({ conversation: conversationId });

    res.json({
      messages: sortedMessages,
      pagination: {
        page: pageNum,
        limit: limitNum,
        total: totalMessages,
        pages: Math.ceil(totalMessages / limitNum)
      }
    });
  } catch (error) {
    console.error('❌ Get messages error:', error);
    res.status(500).json({ error: 'Server error fetching messages' });
  }
};

// ADD THE MISSING FUNCTION
exports.updateConversation = async (req, res) => {
  try {
    const { conversationId } = req.params;
    const { name, description, settings } = req.body;
    const userId = req.user.userId;

    // Check if user is admin/owner of conversation
    const conversation = await Conversation.findOne({
      _id: conversationId,
      'participants.user': userId,
      'participants.role': { $in: ['admin', 'owner'] }
    });

    if (!conversation) {
      return res.status(404).json({ error: 'Conversation not found or insufficient permissions' });
    }

    const updateData = {};
    if (name !== undefined) updateData.name = name;
    if (description !== undefined) updateData.description = description;
    if (settings) updateData.settings = { ...conversation.settings, ...settings };

    const updatedConversation = await Conversation.findByIdAndUpdate(
      conversationId,
      updateData,
      { new: true }
    ).populate('participants.user', 'username displayName avatar status');

    if (!updatedConversation) {
      return res.status(404).json({ error: 'Conversation not found' });
    }

    res.json({
      message: 'Conversation updated successfully',
      conversation: updatedConversation
    });
  } catch (error) {
    console.error('❌ Update conversation error:', error);
    res.status(500).json({ error: 'Server error updating conversation' });
  }
};

// ADD THE MISSING FUNCTION
exports.generateInviteLink = async (req, res) => {
  try {
    const { conversationId } = req.params;
    const { expiresIn = '7d', maxUses = null } = req.body;
    const userId = req.user.userId;

    // Check if user is admin/owner
    const conversation = await Conversation.findOne({
      _id: conversationId,
      'participants.user': userId,
      'participants.role': { $in: ['admin', 'owner'] }
    });

    if (!conversation) {
      return res.status(404).json({ error: 'Conversation not found or insufficient permissions' });
    }

    const inviteCode = generateInviteCode();
    const expiresAt = new Date();
    expiresAt.setDate(expiresAt.getDate() + 7); // Default 7 days

    const inviteLink = {
      code: inviteCode,
      createdBy: userId,
      expiresAt,
      maxUses: maxUses || null,
      uses: 0,
      isActive: true
    };

    conversation.inviteLinks.push(inviteLink);
    await conversation.save();

    res.json({
      message: 'Invite link generated successfully',
      inviteLink: {
        code: inviteCode,
        url: `${process.env.CLIENT_URL || 'http://localhost:3000'}/join/${inviteCode}`,
        expiresAt,
        maxUses
      }
    });
  } catch (error) {
    console.error('❌ Generate invite link error:', error);
    res.status(500).json({ error: 'Server error generating invite link' });
  }
};