const express = require('express'); const router = express.Router(); const db = require('../db'); // POST /api/dms/open — Find-or-create a DM channel between two users router.post('/open', async (req, res) => { const { userId, targetUserId } = req.body; if (!userId || !targetUserId) { return res.status(400).json({ error: 'userId and targetUserId required' }); } if (userId === targetUserId) { return res.status(400).json({ error: 'Cannot DM yourself' }); } // Deterministic channel name so the same pair always maps to one channel const sorted = [userId, targetUserId].sort(); const dmName = `dm-${sorted[0]}-${sorted[1]}`; try { // Check if DM channel already exists const existing = await db.query( 'SELECT id FROM channels WHERE name = $1 AND type = $2', [dmName, 'dm'] ); if (existing.rows.length > 0) { return res.json({ channelId: existing.rows[0].id, created: false }); } // Create the DM channel + participants in a transaction await db.query('BEGIN'); const channelResult = await db.query( 'INSERT INTO channels (name, type) VALUES ($1, $2) RETURNING id', [dmName, 'dm'] ); const channelId = channelResult.rows[0].id; await db.query( 'INSERT INTO dm_participants (channel_id, user_id) VALUES ($1, $2), ($1, $3)', [channelId, userId, targetUserId] ); await db.query('COMMIT'); res.json({ channelId, created: true }); } catch (err) { await db.query('ROLLBACK'); console.error('Error opening DM:', err); res.status(500).json({ error: 'Server error' }); } }); // GET /api/dms/user/:userId — List all DM channels for a user with the other user's info router.get('/user/:userId', async (req, res) => { const { userId } = req.params; try { const result = await db.query(` SELECT c.id AS channel_id, c.name AS channel_name, c.created_at, other_user.id AS other_user_id, other_user.username AS other_username FROM dm_participants my JOIN channels c ON c.id = my.channel_id AND c.type = 'dm' JOIN dm_participants other ON other.channel_id = my.channel_id AND other.user_id != $1 JOIN users other_user ON other_user.id = other.user_id WHERE my.user_id = $1 ORDER BY c.created_at DESC `, [userId]); res.json(result.rows); } catch (err) { console.error('Error fetching DM channels:', err); res.status(500).json({ error: 'Server error' }); } }); module.exports = router;