import { Server } from 'socket.io';
import BaseService from '../services/BaseService.js';

const baseService = new BaseService();

let io;
const userSockets = {};

export function setupWebSocket(server) {
    io = new Server(server, {
        cors: {
            origin: '*',
        },
    });

    io.on('connection', (socket) => {
        socket.on('setUserId', (userId) => {
            if (userId) {
                socket.userId = userId;
                userSockets[userId] = socket.id;
            }
        });
        socket.on('disconnect', () => {
            if (socket.userId) {
                delete userSockets[socket.userId];
            }
        });
    });
}

export function getIo() {
    if (!io) {
        throw new Error('Socket.io ist nicht initialisiert!');
    }
    return io;
}

export function getUserSockets() {
    return userSockets;
}

export async function notifyUser(recipientHashedUserId, event, data) {
    const io = getIo();
    const userSockets = getUserSockets();
    try {
        const recipientUser = await baseService.getUserByHashedId(recipientHashedUserId);
        if (recipientUser) {
            const socketId = userSockets[recipientUser.hashedId];
            if (socketId) {
                setTimeout(() => {
                    io.to(socketId).emit(event, data);
                }, 250);
            }
        } else {
            console.log(`Benutzer mit gehashter ID ${recipientHashedUserId} nicht gefunden.`);
        }
    } catch (err) {
        console.error('Fehler beim Senden der Benachrichtigung:', err);
    }
    console.log('done sending socket');
}

export async function notifyAllUsers(event, data) {
    const io = getIo();
    const userSockets = getUserSockets();

    try {
        for (const [userId, socketId] of Object.entries(userSockets)) {
            io.to(socketId).emit(event, data);
            console.log(`Benachrichtigung an Benutzer mit ID ${userId} gesendet.`);
        }
    } catch (err) {
        console.error('Fehler beim Senden der Benachrichtigung an alle Benutzer:', err);
    }
}