// internal dependencies
const connections = require('./connections.js');

// This will hold a reference to the running WebSocket server
let serverInstance = null;

/*
    * Stop the WebSocket service
    * - Stops heartbeat
    * - Closes all active connections
    * - Closes the WebSocket server
*/
async function stopService () {
    try {
        if (!serverInstance) return { online: false };

        // Stop heartbeat system
        connections.stopHeartbeat();

        // Terminate all active connections
        connections.clearAll();

        // Close WebSocket server
        await new Promise((resolve, reject) => {
            serverInstance.close((err) => {
                if (err) return reject(err);
                resolve();
            });
        });

        serverInstance = null;

        console.log('WebSocket server stopped successfully');

        return { online: false };
    } catch (err) {
        console.error('Error stopping WebSocket server:', err);
        return { online: true, error: err };
    }
};

module.exports = stopService;