import express from 'express'; import cors from 'cors'; import { initDB } from './db.js'; import authRoutes from './routes/auth.js'; import taskRoutes from './routes/tasks.js'; import exportRoutes from './routes/export.js'; import notificationRoutes from './routes/notifications.js'; import { createServer } from 'http'; import { Server } from 'socket.io'; const app = express(); const httpServer = createServer(app); const io = new Server(httpServer, { cors: { origin: "*", methods: ["GET", "POST"] } }); const PORT = process.env.PORT || 3001; app.use(cors()); app.use(express.json()); // Socket.io connection handling io.on('connection', (socket) => { socket.on('join', (userId) => { socket.join(userId); console.log(`User ${userId} joined notification room`); }); }); // Middleware to attach io to req app.use((req, res, next) => { req.io = io; next(); }); // Routes app.use('/api/auth', authRoutes); app.use('/api/tasks', taskRoutes); app.use('/api/export', exportRoutes); app.use('/api/notifications', notificationRoutes); // Health check app.get('/api/health', (_req, res) => { res.json({ status: 'ok', timestamp: new Date().toISOString() }); }); // Initialize DB and start server async function start() { try { await initDB(); if (process.env.NODE_ENV !== 'test') { httpServer.listen(PORT, () => { console.log(`🚀 Backend server running on port ${PORT} with Socket.io`); }); } } catch (err) { console.error('❌ Failed to start server:', err); process.exit(1); } } if (process.env.NODE_ENV !== 'test') { start(); } export { app, start, io };