// Test script to simulate 4 players joining matchmaker
const { Client } = require('@heroiclabs/nakama-js');
const { v4: uuidv4 } = require('uuid');

async function simulatePlayer(playerId) {
    const client = new Client('defaultkey', 'localhost', '7350', false);
    const deviceId = uuidv4();

    console.log(`Player ${playerId}: Authenticating with deviceId ${deviceId}`);
    const session = await client.authenticateDevice(deviceId, true, deviceId);
    console.log(`Player ${playerId}: Authenticated as ${session.user_id}`);

    const socket = client.createSocket(false, false);
    await socket.connect(session, true);
    console.log(`Player ${playerId}: Socket connected`);

    socket.onmatchmakermatched = async (matched) => {
        console.log(`Player ${playerId}: MATCHED! Match ID: ${matched.match_id}`);
        try {
            const match = await socket.joinMatch(matched.match_id, matched.token);
            console.log(`Player ${playerId}: Joined match ${match.match_id}`);
        } catch (e) {
            console.error(`Player ${playerId}: Failed to join match`, e);
        }
    };

    socket.onmatchdata = (data) => {
        console.log(`Player ${playerId}: Received match data`, data.op_code);
    };

    const ticket = await socket.addMatchmaker('*', 4, 4);
    console.log(`Player ${playerId}: Added to matchmaker with ticket ${ticket.ticket}`);

    return socket;
}

async function main() {
    console.log('Starting 4 player simulation...');

    const promises = [];
    for (let i = 1; i <= 4; i++) {
        promises.push(simulatePlayer(i));
    }

    try {
        await Promise.all(promises);
        console.log('All 4 players added to matchmaker. Waiting for match...');

        // Keep the script running to receive match events
        await new Promise(resolve => setTimeout(resolve, 30000));
    } catch (error) {
        console.error('Error:', error);
    }
}

main();
