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

const baseService = new BaseService();

let io;
const userSockets = {};
const DEBUG_SOCKETS = process.env.DEBUG_SOCKETS === 'true';

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

    io.on('connection', (socket) => {
        if (DEBUG_SOCKETS) console.log('[socket.io] connection established:', socket.id, 'from', socket.handshake.address);

        socket.on('setUserId', (userId) => {
            if (userId) {
                socket.userId = userId;
                userSockets[userId] = socket.id;
                if (DEBUG_SOCKETS) console.log('[socket.io] setUserId received:', userId, '→ socket', socket.id);
            }
        });
        socket.on('disconnect', () => {
            if (socket.userId) {
                delete userSockets[socket.userId];
                if (DEBUG_SOCKETS) console.log('[socket.io] disconnected:', socket.id, 'for userId', 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) {
                if (DEBUG_SOCKETS) console.log('[socket.io] notifyUser → emit:', event, 'to socket', socketId, 'user', recipientUser.hashedId, 'data:', JSON.stringify(data));
                setTimeout(() => {
                    io.to(socketId).emit(event, data);
                }, 250);
            } else {
                if (DEBUG_SOCKETS) console.warn('[socket.io] notifyUser: no socket registered for user', recipientUser.hashedId);
            }
        } else {
            if (DEBUG_SOCKETS) console.log(`Benutzer mit gehashter ID ${recipientHashedUserId} nicht gefunden.`);
        }
    } catch (err) {
        console.error('Fehler beim Senden der Benachrichtigung:', err);
    }
    if (DEBUG_SOCKETS) console.log('[socket.io] notifyUser done');
}

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);
    }
}