import { WebSocketServer } from 'ws';
import { randomUUID } from 'crypto';

export class WSServer {
	constructor({ port, onMessage }) {
		this.wss = new WebSocketServer({ port });
		this.clients = new Map(); // clientId ? ws

		this.wss.on('connection', (ws) => {
			const clientId = randomUUID();
			this.clients.set(clientId, ws);
			console.log(`🟢 Client connecté : ${clientId}`);

			ws.on('message', (rawData) => {
				try {
					const message = JSON.parse(rawData);
					if (typeof onMessage === 'function') {
						onMessage({ clientId, message });
					}
				} catch (e) {
					console.error(`❌ Erreur de parsing JSON du client ${clientId} :`, e);
				}
			});

			ws.on('close', () => {
				console.log(`🔴 Client déconnecté : ${clientId}`);
				this.clients.delete(clientId);
			});

			ws.on('error', (err) => {
				console.error(`⚠️ Erreur WebSocket (client ${clientId}) :`, err);
			});
		});

		console.log(`✅ WebSocketServer lancé sur le port ${port}`);
	}

	sendToClient(clientId, messageObj) {
		//console.log(`Send to client [${clientId}]:`, messageObj);
		const client = this.clients.get(clientId);
		if (client && client.readyState === client.OPEN) {
			client.send(JSON.stringify(messageObj));
		}
	}

	broadcast(messageObj, { exclude = null } = {}) {
		const message = JSON.stringify(messageObj);
		for (const [clientId, client] of this.clients.entries()) {
			if (client.readyState === client.OPEN && clientId !== exclude) {
				client.send(message);
			}
		}
	}

	getClientIds() {
		return Array.from(this.clients.keys());
	}
}