/**
 * SSEClient - SSE连接管理
 * 只负责SSE连接管理，提供事件驱动架构
 */

import {
  sseService,
  WSChatMessage,
  WSGroupChatMessage,
  WSReadMessage,
  WSGroupReadMessage,
  WSRecallMessage,
  WSGroupRecallMessage,
  WSGroupTypingMessage,
  WSGroupNoticeMessage,
  WSMessageType,
} from '../../services/sseService';

// 事件处理器类型
type EventHandler<T> = (data: T) => void;

// SSE事件类型
export interface SSEEvents {
  'chat': WSChatMessage;
  'group_message': WSGroupChatMessage;
  'read': WSReadMessage;
  'group_read': WSGroupReadMessage;
  'recall': WSRecallMessage;
  'group_recall': WSGroupRecallMessage;
  'group_typing': WSGroupTypingMessage;
  'group_notice': WSGroupNoticeMessage;
  'connected': void;
  'disconnected': void;
  'error': Error;
}

export type SSEEventType = keyof SSEEvents;

class SSEClient {
  private handlers: Map<SSEEventType, Set<EventHandler<any>>> = new Map();
  private unsubscribeFns: Array<() => void> = [];
  private isInitialized = false;

  /**
   * 初始化SSE监听
   */
  initialize(): void {
    if (this.isInitialized) return;

    // 监听私聊消息
    const unsubChat = sseService.on('chat', (message) => {
      this.emit('chat', message);
    });

    // 监听群聊消息
    const unsubGroupMessage = sseService.on('group_message', (message) => {
      this.emit('group_message', message);
    });

    // 监听私聊已读回执
    const unsubRead = sseService.on('read', (message) => {
      this.emit('read', message);
    });

    // 监听群聊已读回执
    const unsubGroupRead = sseService.on('group_read', (message) => {
      this.emit('group_read', message);
    });

    // 监听私聊消息撤回
    const unsubRecall = sseService.on('recall', (message) => {
      this.emit('recall', message);
    });

    // 监听群聊消息撤回
    const unsubGroupRecall = sseService.on('group_recall', (message) => {
      this.emit('group_recall', message);
    });

    // 监听群聊输入状态
    const unsubGroupTyping = sseService.on('group_typing', (message) => {
      this.emit('group_typing', message);
    });

    // 监听群通知
    const unsubGroupNotice = sseService.on('group_notice', (message) => {
      this.emit('group_notice', message);
    });

    // 监听连接状态
    const unsubConnect = sseService.onConnect(() => {
      this.emit('connected', undefined);
    });

    const unsubDisconnect = sseService.onDisconnect(() => {
      this.emit('disconnected', undefined);
    });

    this.unsubscribeFns = [
      unsubChat,
      unsubGroupMessage,
      unsubRead,
      unsubGroupRead,
      unsubRecall,
      unsubGroupRecall,
      unsubGroupTyping,
      unsubGroupNotice,
      unsubConnect,
      unsubDisconnect,
    ];

    this.isInitialized = true;
  }

  /**
   * 销毁SSE监听
   */
  destroy(): void {
    this.unsubscribeFns.forEach((fn) => fn());
    this.unsubscribeFns = [];
    this.handlers.clear();
    this.isInitialized = false;
  }

  /**
   * 订阅事件
   */
  on<T extends SSEEventType>(
    event: T,
    handler: EventHandler<SSEEvents[T]>
  ): () => void {
    if (!this.handlers.has(event)) {
      this.handlers.set(event, new Set());
    }
    this.handlers.get(event)!.add(handler);

    return () => {
      this.handlers.get(event)?.delete(handler);
    };
  }

  /**
   * 触发事件
   */
  private emit<T extends SSEEventType>(
    event: T,
    data: SSEEvents[T]
  ): void {
    const handlers = this.handlers.get(event);
    if (handlers) {
      handlers.forEach((handler) => {
        try {
          handler(data);
        } catch (error) {
          console.error(`[SSEClient] 事件处理器执行失败: ${event}`, error);
        }
      });
    }
  }

  /**
   * 检查连接状态
   */
  isConnected(): boolean {
    return sseService.isConnected();
  }

  /**
   * 启动SSE连接
   */
  async connect(): Promise<boolean> {
    return sseService.start();
  }

  /**
   * 断开SSE连接
   */
  disconnect(): void {
    sseService.stop();
  }
}

export const sseClient = new SSEClient();
export default sseClient;
