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