import { Server as SocketServer } from 'socket.io';
import { Server as HTTPServer } from 'http';
import logger from './logger.js';
import { getFrontendBaseUrl } from './frontendUrl.js';

let io: SocketServer | null = null;

/**
 * Initializes the Socket.io server and attaches it to the provided HTTP server.
 * @param httpServer The HTTP server to attach Socket.io to.
 */
export const initSocket = (httpServer: HTTPServer) => {
    io = new SocketServer(httpServer, {
        cors: {
            origin: getFrontendBaseUrl(),
            methods: ['GET', 'POST', 'PUT'],
            credentials: true
        }
    });

    io.on('connection', (socket) => {
        logger.info(`Socket connected: ${socket.id}`);

        // Join room based on requestId (applicationId, etc.)
        socket.on('join_room', (roomId: string) => {
            socket.join(roomId);
            logger.info(`Socket ${socket.id} joined room: ${roomId}`);
        });

        socket.on('leave_room', (roomId: string) => {
            socket.leave(roomId);
            logger.info(`Socket ${socket.id} left room: ${roomId}`);
        });

        socket.on('disconnect', () => {
            logger.info(`Socket disconnected: ${socket.id}`);
        });
    });

    return io;
};

/**
 * Returns the initialized Socket.io instance.
 * @throws Error if Socket.io has not been initialized.
 */
export const getIO = (): SocketServer => {
    if (!io) {
        throw new Error('Socket.io has not been initialized. Please call initSocket first.');
    }
    return io;
};
