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