/**
 * Socket.io client test script
 */

const io = require('socket.io-client');

// Use the token generated from the server
const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ0ZXN0LXVzZXItMTIzIiwiaWF0IjoxNzU0OTc5Mzg0LCJleHAiOjE3NTQ5ODI5ODR9.Ih6p5t-NkOCevL88Uwyj2ffDOUGOlsfw4_VuvGkxj-w';

console.log('🔔 Testing Socket.io Notification Connection...\n');

const socket = io('http://localhost:3001', {
  auth: {
    token: TOKEN
  },
  transports: ['websocket', 'polling']
});

socket.on('connect', () => {
  console.log('✅ Connected successfully!');
  console.log('   Socket ID:', socket.id);
  console.log('   Transport:', socket.io.engine.transport.name);
  
  // Test sending a notification to ourselves
  setTimeout(() => {
    console.log('\n📤 Sending test notification...');
    socket.emit('test:notification', {
      type: 'task_assigned',
      priority: 'high',
      title: 'New Task Assigned',
      message: 'You have been assigned to: Fix the notification system',
      metadata: {
        taskId: '123',
        projectId: '456'
      }
    });
  }, 1000);

  // Test marking notification as read
  setTimeout(() => {
    console.log('\n📖 Testing mark as read...');
    socket.emit('notification:markRead', 'test-notification-123');
  }, 2000);

  // Test updating preferences
  setTimeout(() => {
    console.log('\n⚙️ Testing preference update...');
    socket.emit('notification:updatePreferences', {
      email: { enabled: true, frequency: 'instant' },
      realtime: { enabled: true, sound: true }
    });
  }, 3000);

  // Disconnect after tests
  setTimeout(() => {
    console.log('\n👋 Tests complete, disconnecting...');
    socket.disconnect();
    process.exit(0);
  }, 5000);
});

socket.on('notification:new', (notification) => {
  console.log('\n📬 Received notification:');
  console.log('   ID:', notification.id);
  console.log('   Type:', notification.type);
  console.log('   Priority:', notification.priority);
  console.log('   Title:', notification.title);
  console.log('   Message:', notification.message);
});

socket.on('notification:read', (notificationId) => {
  console.log('✅ Notification marked as read:', notificationId);
});

socket.on('preferences:updated', (preferences) => {
  console.log('✅ Preferences updated:', JSON.stringify(preferences, null, 2));
});

socket.on('connect_error', (error) => {
  console.error('❌ Connection error:', error.message);
  process.exit(1);
});

socket.on('disconnect', (reason) => {
  console.log('🔌 Disconnected:', reason);
});