import mqtt from 'mqtt';

// Get session UUID from command line argument
const sessionUuid = process.argv[2];

if (!sessionUuid) {
    console.error('Please provide a session UUID as argument');
    console.error('Usage: node cancel-load-test-session.js <sessionUuid>');
    process.exit(1);
}

// Create MQTT client with unique ID
const client = mqtt.connect('mqtt://127.0.0.1:1883', {
    clientId: 'error-sender-' + Math.random().toString(16).substring(2, 8)
});

// Handle connection errors
client.on('error', function (err) {
    console.error('MQTT client error:', err);
    process.exit(1);
});

// Handle reconnection attempts
client.on('reconnect', function () {
    console.log('Attempting to reconnect to MQTT broker...');
});

client.on('connect', function () {
    console.log('Connected to MQTT broker');
    let topic = sessionUuid + '/all';
    console.log(`Sending sync message - Topic: ${topic}`);
    client.publish(topic, "sync", { qos: 1 }, (err) => {
        if (err) {
            console.error('Error sending message:', err);
            process.exit(1);
        } else {
            console.log('SYNC message sent successfully');
            // Give a small delay to ensure message is delivered before sending error
            setTimeout(() => {
                // Send error message with session UUID as payload
                topic = 'error';
                console.log(`Sending error message - Topic: ${topic}, Session: ${sessionUuid}`);
                client.publish(topic, sessionUuid, { qos: 1 }, (err) => {
                    if (err) {
                        console.error('Error sending message:', err);
                        process.exit(1);
                    } else {
                        console.log('Error message sent successfully');
                        // Give a small delay to ensure message is delivered before closing
                        setTimeout(() => {
                            client.end(true, () => {
                                console.log('Connection closed');
                                process.exit(0);
                            });
                        }, 1000);
                    }
                });
            }, 1000);
        }
    });
});