const { getRooms, getRoom, updateRoom, createNewRoom, deleteRoom } = require('../services/roomService');
const { sendToOnePlayerRooms, sendToOnePlayerData, sendWinner } = require('../socket/emits');

module.exports = socket => {
    const req = socket.request;

    const handleGetData = async () => {
        const room = await getRoom(req.session.roomId);
        // Handle the situation when the server crashes and any player reconnects after the time has expired
        // Typically, the responsibility for changing players is managed by gameHandler.js.
        if(!room) return;
        if (room.nextMoveTime <= Date.now()) {
            room.changeMovingPlayer();
            await updateRoom(room);
        }
        sendToOnePlayerData(socket.id, room);
        if (room.winner) sendWinner(socket.id, room.winner);
    };

    const handleGetAllRooms = async () => {
        const rooms = await getRooms();
        sendToOnePlayerRooms(socket.id, rooms);
    };

    const handleCreateRoom = async data => {
        await createNewRoom(data);
        sendToOnePlayerRooms(socket.id, await getRooms());
    };

    const handleDeleteRoom = async roomId => {
        try {
            console.log('🗑️ Attempting to delete room:', roomId);
            const result = await deleteRoom(roomId);
            console.log('✅ Room deleted successfully:', result);
            const updatedRooms = await getRooms();
            console.log('📋 Updated room count:', updatedRooms.length);
            console.log('📤 Sending updated rooms to socket:', socket.id);
            sendToOnePlayerRooms(socket.id, updatedRooms);
        } catch (error) {
            console.error('❌ Error deleting room:', error);
            socket.emit('error:deleteRoom', 'Failed to delete room');
        }
    };

    socket.on('room:data', handleGetData);
    socket.on('room:rooms', handleGetAllRooms);
    socket.on('room:create', handleCreateRoom);
    socket.on('room:delete', handleDeleteRoom);
};
