const jwt = require('jsonwebtoken'); const { Pool } = require('pg'); const pool = new Pool({ connectionString: process.env.DATABASE_URL, }); async function addFriend(req, res) { const { friend_uid } = req.body; const token = req.headers['authorization'] && req.headers['authorization'].split(' ')[1]; if (!token) { return res.status(403).json({ error: 'Access denied. No token provided.' }); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET); const userUid = decoded.uid; const client = await pool.connect(); try { const result = await client.query( 'SELECT friend_list FROM users WHERE uid = $1;', [userUid] ); let friends = result.rows[0]?.friend_list || {}; if (Object.values(friends).includes(friend_uid)) { return res.status(400).json({ error: 'Friend already in the list.' }); } const friendKey = `friend${Object.keys(friends).length}`; friends[friendKey] = friend_uid; const friendsJson = JSON.stringify(friends); await client.query( 'UPDATE users SET friend_list = $1 WHERE uid = $2;', [friendsJson, userUid] ); res.status(200).json({ message: 'Friend added successfully!' }); } finally { client.release(); } } catch (error) { console.error('Error adding friend:', error); res.status(500).json({ error: 'Server error' }); } } async function getFriendDetails(friendUid) { const client = await pool.connect(); try { const result = await client.query('SELECT display_name, uid FROM users WHERE uid = $1', [friendUid]); if (result.rows.length > 0) { return result.rows[0]; } return null; } finally { client.release(); } } async function getFriendsList(req, res) { const userId = req.user.id; try { const client = await pool.connect(); try { const result = await client.query( 'SELECT friend_list FROM users WHERE uid = $1;', [userId] ); const user = result.rows[0]; if (!user || !user.friend_list) { return res.status(404).json({ error: 'No friends found.' }); } const friends = JSON.parse(user.friend_list); const friendsDetails = []; for (const key in friends) { const friendUid = friends[key]; const friendDetails = await getFriendDetails(friendUid); if (friendDetails) { friendsDetails.push(friendDetails); } } return res.status(200).json({ friends: friendsDetails }); } finally { client.release(); } } catch (error) { console.error('Error fetching friends:', error); res.status(400).json({ error: error.message }); } } module.exports = { addFriend };