/**
 * SSE Demo Script
 * Demonstrates the SSE service functionality
 */

const sseService = require('./services/sseService');

console.log('=== SSE Service Demo ===\n');

// Mock response objects
const createMockRes = (userId) => ({
  write: (data) => console.log(`[${userId}] Received:`, data.trim()),
});

// 1. Add clients
console.log('1. Adding clients...');
const res1 = createMockRes('user1');
const res2 = createMockRes('user2');
const res3 = createMockRes('user3');

sseService.addClient('user1', res1);
sseService.addClient('user2', res2);
sseService.addClient('user3', res3);

let stats = sseService.getStats();
console.log('Stats after adding clients:', stats);
console.log('');

// 2. Subscribe to topics
console.log('2. Subscribing to topics...');
sseService.subscribe('user1', ['events', 'posts']);
sseService.subscribe('user2', ['events']);
sseService.subscribe('user3', ['posts']);

stats = sseService.getStats();
console.log('Stats after subscriptions:', stats);
console.log('');

// 3. Broadcast to all
console.log('3. Broadcasting to all clients...');
sseService.broadcast('announcement', { message: 'Hello everyone!' });
console.log('');

// 4. Broadcast to topic
console.log('4. Broadcasting to "events" topic (user1, user2)...');
sseService.broadcastToTopic('events', 'eventUpdate', { eventId: 123, status: 'started' });
console.log('');

console.log('5. Broadcasting to "posts" topic (user1, user3)...');
sseService.broadcastToTopic('posts', 'newPost', { postId: 456, author: 'Alice' });
console.log('');

// 6. Send to specific user
console.log('6. Sending to specific user (user2)...');
sseService.sendToUser('user2', 'notification', { text: 'You have a new message' });
console.log('');

// 7. Unsubscribe
console.log('7. Unsubscribing user1 from "events"...');
sseService.unsubscribe('user1', ['events']);
stats = sseService.getStats();
console.log('Stats after unsubscribe:', stats);
console.log('');

// 8. Remove client
console.log('8. Removing user3...');
sseService.removeClient('user3');
stats = sseService.getStats();
console.log('Stats after removing user3:', stats);
console.log('');

// Clean up
sseService.removeClient('user1');
sseService.removeClient('user2');

console.log('=== Demo Complete ===');
