const express = require('express'); const router = express.Router(); const { Op } = require('sequelize'); module.exports = (sequelize) => { const { User, Friendship, FriendRequest } = sequelize.models; // POST /api/friend-requests router.post('/', async (req, res) => { try { const { identifier } = req.body; const toUser = await User.findOne({ where: { [Op.or]: [{ email: identifier }, { name: identifier }] } }); if (!toUser) return res.status(404).json({ message: 'Utente non trovato.' }); if (toUser.id === req.userId) return res.status(400).json({ message: 'Non puoi aggiungere te stesso.'}); const user1Id = Math.min(req.userId, toUser.id); const user2Id = Math.max(req.userId, toUser.id); const friendshipExists = await Friendship.findOne({ where: { user1Id, user2Id } }); if (friendshipExists) return res.status(400).json({ message: 'Siete già amici.'}); const requestExists = await FriendRequest.findOne({ where: { [Op.or]: [{ fromUserId: req.userId, toUserId: toUser.id }, { fromUserId: toUser.id, toUserId: req.userId }] } }); if (requestExists) return res.status(400).json({ message: 'Richiesta già inviata.'}); const friendRequest = await FriendRequest.create({ fromUserId: req.userId, toUserId: toUser.id }); const populatedReq = await FriendRequest.findByPk(friendRequest.id, { include: [{ model: User, as: 'fromUser' }, { model: User, as: 'toUser' }] }); res.status(201).json(populatedReq); } catch (error) { res.status(400).json({ message: 'Error sending friend request', error: error.message }); } }); // POST /api/friend-requests/:id/accept router.post('/:id/accept', async (req, res) => { const t = await sequelize.transaction(); try { const request = await FriendRequest.findByPk(req.params.id, { transaction: t }); if (!request || request.toUserId !== req.userId) { await t.rollback(); return res.status(404).json({ message: 'Request not found or not for you.' }); } const user1Id = Math.min(request.fromUserId, request.toUserId); const user2Id = Math.max(request.fromUserId, request.toUserId); await Friendship.create({ user1Id, user2Id }, { transaction: t }); await request.destroy({ transaction: t }); await t.commit(); const newFriend = await User.findByPk(request.fromUserId); res.status(200).json({ message: 'Friend request accepted', newFriend }); } catch (error) { await t.rollback(); res.status(400).json({ message: 'Error accepting friend request', error: error.message }); } }); // DELETE /api/friend-requests/:id router.delete('/:id', async (req, res) => { try { const count = await FriendRequest.destroy({ where: { id: req.params.id } }); if (count === 0) return res.status(404).json({ message: 'Request not found.' }); res.status(200).json({ message: 'Friend request cancelled/declined.' }); } catch (error) { res.status(400).json({ message: 'Error deleting friend request', error: error.message }); } }); return router; };