// services/webSocketService.js
import { Server } from 'socket.io';
import amqp from 'amqplib/callback_api.js';

const RABBITMQ_URL = 'amqp://localhost';
const QUEUE = 'chat_messages';

export function setupWebSocket(server) {
    const io = new Server(server);

    amqp.connect(RABBITMQ_URL, (err, connection) => {
        if (err) throw err;

        connection.createChannel((err, channel) => {
            if (err) throw err;

            channel.assertQueue(QUEUE, { durable: false });

            io.on('connection', (socket) => {
                console.log('Client connected via WebSocket');

                // Konsumiert Nachrichten aus RabbitMQ und sendet sie an den WebSocket-Client
                channel.consume(QUEUE, (msg) => {
                    const message = JSON.parse(msg.content.toString());
                    io.emit('newMessage', message);  // Broadcast an alle Clients
                }, { noAck: true });

                // Empfangt eine Nachricht vom WebSocket-Client und sendet sie an die RabbitMQ-Warteschlange
                socket.on('newMessage', (message) => {
                    channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify(message)));
                });

                socket.on('disconnect', () => {
                    console.log('Client disconnected');
                });
            });
        });
    });
}
