#!/usr/bin/env node

/**
 * WebSocket Test Client
 * 
 * Tests the WebSocket event system for the Jackbox Game Picker API
 * 
 * Usage:
 *   JWT_TOKEN="your_token" node test-websocket.js
 */

const WebSocket = require('ws');

const API_URL = process.env.API_URL || 'ws://localhost:5000';
const JWT_TOKEN = process.env.JWT_TOKEN || '';

if (!JWT_TOKEN) {
  console.error('\n❌ ERROR: JWT_TOKEN not set!');
  console.error('\nGet your token:');
  console.error('  curl -X POST "http://localhost:5000/api/auth/login" \\');
  console.error('    -H "Content-Type: application/json" \\');
  console.error('    -d \'{"key":"YOUR_ADMIN_KEY"}\'');
  console.error('\nThen run:');
  console.error('  JWT_TOKEN="your_token" node test-websocket.js\n');
  process.exit(1);
}

console.log('\n🚀 WebSocket Test Client');
console.log('═══════════════════════════════════════════════════════\n');
console.log(`Connecting to: ${API_URL}/api/sessions/live`);
console.log('');

const ws = new WebSocket(`${API_URL}/api/sessions/live`);

ws.on('open', () => {
  console.log('✅ Connected to WebSocket server\n');
  
  // Step 1: Authenticate
  console.log('📝 Step 1: Authenticating...');
  ws.send(JSON.stringify({
    type: 'auth',
    token: JWT_TOKEN
  }));
});

ws.on('message', (data) => {
  try {
    const message = JSON.parse(data.toString());
    
    switch (message.type) {
      case 'auth_success':
        console.log('✅ Authentication successful\n');
        
        // Step 2: Subscribe to session (you can change this ID)
        console.log('📝 Step 2: Subscribing to session 1...');
        ws.send(JSON.stringify({
          type: 'subscribe',
          sessionId: 1
        }));
        break;
        
      case 'auth_error':
        console.error('❌ Authentication failed:', message.message);
        process.exit(1);
        break;
        
      case 'subscribed':
        console.log(`✅ Subscribed to session ${message.sessionId}\n`);
        console.log('🎧 Listening for events...');
        console.log('   Add a game in the Picker page to see events here');
        console.log('   Press Ctrl+C to exit\n');
        
        // Start heartbeat
        setInterval(() => {
          ws.send(JSON.stringify({ type: 'ping' }));
        }, 30000);
        break;
        
      case 'game.added':
        console.log('\n🎮 GAME ADDED EVENT RECEIVED!');
        console.log('═══════════════════════════════════════════════════════');
        console.log('Game:', message.data.game.title);
        console.log('Pack:', message.data.game.pack_name);
        console.log('Players:', `${message.data.game.min_players}-${message.data.game.max_players}`);
        console.log('Session ID:', message.data.session.id);
        console.log('Games Played:', message.data.session.games_played);
        console.log('Timestamp:', message.timestamp);
        console.log('═══════════════════════════════════════════════════════\n');
        break;
        
      case 'pong':
        console.log('💓 Heartbeat');
        break;
        
      case 'error':
        console.error('❌ Error:', message.message);
        break;
        
      default:
        console.log('📨 Received:', message);
    }
  } catch (err) {
    console.error('Failed to parse message:', err);
  }
});

ws.on('error', (err) => {
  console.error('\n❌ WebSocket error:', err.message);
  process.exit(1);
});

ws.on('close', () => {
  console.log('\n👋 Connection closed');
  process.exit(0);
});

// Handle Ctrl+C
process.on('SIGINT', () => {
  console.log('\n\n⚠️  Closing connection...');
  ws.close();
});

