File size: 7,255 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
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.findOne({
        type: 'direct',
        participants: {
          $all: [
            { $elemMatch: { user: userId } },
            { $elemMatch: { user: participantIds[0] } }
          ]
        }
      }).populate('participants.user', 'username displayName avatar status');

      if (existingConversation) {
        return res.json({ 
          message: 'Conversation already exists',
          conversation: existingConversation 
        });
      }
    }

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

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

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

    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')
    .populate('lastMessage')
    .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')
    .populate('createdBy', 'username displayName');

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

    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' });
    }

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

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

    res.json({
      messages: sortedMessages,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: await Message.countDocuments({ conversation: conversationId })
      }
    });
  } catch (error) {
    console.error('Get messages error:', error);
    res.status(500).json({ error: 'Server error fetching messages' });
  }
};

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) 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');

    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' });
  }
};

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}/join/${inviteCode}`,
        expiresAt,
        maxUses
      }
    });
  } catch (error) {
    console.error('Generate invite link error:', error);
    res.status(500).json({ error: 'Server error generating invite link' });
  }
};