import { Server as HTTPServer } from "http"; import { Server, Socket } from "socket.io"; export type SocketServer = Server; export type SocketClient = Socket; export function setupSocketIO(httpServer: HTTPServer): SocketServer { const io = new Server(httpServer, { cors: { origin: process.env.CLIENT_URL || "*", methods: ["GET", "POST"], }, }); io.on("connection", (socket: SocketClient) => { console.log(`Client connected: ${socket.id}`); // Join a draft room socket.on("join-draft", (seasonId: string) => { const roomName = `draft-${seasonId}`; socket.join(roomName); console.log(`Socket ${socket.id} joined draft room: ${roomName}`); // Notify others in the room socket.to(roomName).emit("user-joined", { socketId: socket.id }); }); // Leave a draft room socket.on("leave-draft", (seasonId: string) => { const roomName = `draft-${seasonId}`; socket.leave(roomName); console.log(`Socket ${socket.id} left draft room: ${roomName}`); }); // Draft Actions - Phase 9 // These events will be handled by API routes and then broadcast back via socket // The client will call API routes which will then use getSocketIO() to broadcast socket.on("make-pick", (_data) => { console.log("make-pick event received, should use API route instead"); }); socket.on("commissioner-start-draft", (_data) => { console.log("commissioner-start-draft event received, should use API route instead"); }); socket.on("commissioner-pause-draft", (_data) => { console.log("commissioner-pause-draft event received, should use API route instead"); }); socket.on("commissioner-force-pick", (_data) => { console.log("commissioner-force-pick event received, should use API route instead"); }); // Handle disconnection socket.on("disconnect", () => { console.log(`Client disconnected: ${socket.id}`); }); }); return io; } // Export a singleton instance that will be set by the server let ioInstance: SocketServer | null = null; export function setSocketIO(io: SocketServer) { ioInstance = io; } export function getSocketIO(): SocketServer { if (!ioInstance) { throw new Error("Socket.IO has not been initialized"); } return ioInstance; }