const express = require('express'); const { prisma } = require('../utils/db'); const { authenticate } = require('../middleware/auth'); const router = express.Router(); // GET /api/events - List all events router.get('/', async (req, res, next) => { try { const events = await prisma.event.findMany({ orderBy: { startDate: 'asc', }, select: { id: true, name: true, location: true, startDate: true, endDate: true, worldsdcId: true, participantsCount: true, description: true, createdAt: true, }, }); res.json({ success: true, count: events.length, data: events, }); } catch (error) { next(error); } }); // GET /api/events/:id - Get event by ID router.get('/:id', async (req, res, next) => { try { const { id } = req.params; const event = await prisma.event.findUnique({ where: { id: parseInt(id), }, include: { chatRooms: true, _count: { select: { matches: true, }, }, }, }); if (!event) { return res.status(404).json({ success: false, error: 'Event not found', }); } res.json({ success: true, data: event, }); } catch (error) { next(error); } }); // GET /api/events/:eventId/messages - Get event chat messages with pagination router.get('/:eventId/messages', authenticate, async (req, res, next) => { try { const { eventId } = req.params; const { before, limit = 20 } = req.query; // Find event chat room const chatRoom = await prisma.chatRoom.findFirst({ where: { eventId: parseInt(eventId), type: 'event', }, }); if (!chatRoom) { return res.status(404).json({ success: false, error: 'Chat room not found', }); } // Build query with pagination const where = { roomId: chatRoom.id }; if (before) { where.id = { lt: parseInt(before) }; } const messages = await prisma.message.findMany({ where, include: { user: { select: { id: true, username: true, avatar: true, }, }, }, orderBy: { createdAt: 'desc' }, take: parseInt(limit), }); // Return in chronological order (oldest first) res.json({ success: true, data: messages.reverse().map(msg => ({ id: msg.id, roomId: msg.roomId, userId: msg.user.id, username: msg.user.username, avatar: msg.user.avatar, content: msg.content, type: msg.type, createdAt: msg.createdAt, })), hasMore: messages.length === parseInt(limit), }); } catch (error) { next(error); } }); module.exports = router;