import { Server } from 'socket.io';
import { ChatRealtimeService } from './chat-realtime.service';

describe('ChatRealtimeService', () => {
  it('silently skips delivery until a socket server is bound', () => {
    const service = new ChatRealtimeService();

    expect(() => service.emitNewMessage('conversation-1', { id: 'message-1' })).not.toThrow();
  });

  it('emits a new message only to the matching conversation room', () => {
    const service = new ChatRealtimeService();
    const emit = jest.fn();
    const to = jest.fn().mockReturnValue({ emit });
    const server = { to } as unknown as Server;
    const message = { id: 'message-1', body: 'hello' };

    service.bindServer(server);
    service.emitNewMessage('conversation-42', message);

    expect(to).toHaveBeenCalledWith('conversation:conversation-42');
    expect(emit).toHaveBeenCalledWith('new_message', message);
  });

  it('does not hide socket delivery errors', () => {
    const service = new ChatRealtimeService();
    const server = {
      to: jest.fn(() => {
        throw new Error('socket unavailable');
      }),
    } as unknown as Server;
    service.bindServer(server);

    expect(() => service.emitNewMessage('conversation-1', {})).toThrow('socket unavailable');
  });
});
