import { WebSocket, WebSocketServer } from 'ws';

let wss;

export function initWebSocket(server) {
    wss = new WebSocketServer({ server });

    wss.on('connection', (ws, req) => {
        console.log('✅ New WebSocket client connected');

        ws.on('close', () => {
            console.log('Client disconnected');
        });
    });

    console.log('WebSocket server initialized');
}

// Broadcast a message to all connected clients
export function broadcast(reqType, data) {
     if (!wss) return;

    const payload = typeof data === 'string' ? data : JSON.stringify(data);
    const message = `${reqType}|${payload}`;

    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
        client.send(message);
        }
    });
}
