/**
 * 会话操作服务
 * 处理会话的 CRUD 操作
 * 
 * 重构说明：
 * - 直接使用 zustand store 替代 IMessageStateManager
 * - 移除了 SubscriptionManager 调用，Zustand 的 set() 会自动触发组件重渲染
 */

import type { ConversationResponse } from '../../../types/dto';
import { messageService } from '@/services/message';
import { conversationRepository } from '@/database';
import type { IConversationOperations } from '../types';
import { useMessageStore, normalizeConversationId } from '../store';

export class ConversationOperations implements IConversationOperations {
  /**
   * 创建私聊会话
   */
  async createConversation(userId: string): Promise<ConversationResponse | null> {
    const store = useMessageStore.getState();
    
    try {
      const conversation = await messageService.createConversation(userId);

      // 添加到会话列表
      store.updateConversation(conversation);

      return conversation;
    } catch (error) {
      console.error('[ConversationOperations] 创建会话失败:', error);
      return null;
    }
  }

  /**
   * 本地更新会话信息
   */
  updateConversation(conversationId: string, updates: Partial<ConversationResponse>): void {
    const store = useMessageStore.getState();
    const conversation = store.getConversation(conversationId);
    if (!conversation) {
      console.warn('[ConversationOperations] 更新会话失败，会话不存在:', conversationId);
      return;
    }

    const updatedConv: ConversationResponse = {
      ...conversation,
      ...updates,
    };

    store.updateConversation(updatedConv);
  }

  /**
   * 仅自己删除会话后的本地状态回收
   */
  removeConversation(conversationId: string): void {
    const store = useMessageStore.getState();
    store.removeConversation(conversationId);

    // 删除本地数据库中的会话
    conversationRepository.delete(conversationId).catch(error => {
      console.error('[ConversationOperations] 删除本地会话失败:', error);
    });
  }

  /**
   * 清空会话列表
   */
  clearConversations(): void {
    const store = useMessageStore.getState();
    store.reset();
  }

  /**
   * 更新单个会话未读数
   */
  updateUnreadCount(conversationId: string, count: number): void {
    const store = useMessageStore.getState();
    const conversation = store.getConversation(conversationId);
    if (!conversation) {
      console.warn('[ConversationOperations] 更新未读数失败，会话不存在:', conversationId);
      return;
    }

    const prevUnreadCount = conversation.unread_count || 0;
    const diff = count - prevUnreadCount;

    // 更新会话未读数
    const updatedConv: ConversationResponse = {
      ...conversation,
      unread_count: count,
    };
    store.updateConversation(updatedConv);

    // 更新总未读数
    const currentUnread = store.getUnreadCount();
    store.setUnreadCount(
      Math.max(0, currentUnread.total + diff),
      currentUnread.system
    );
  }

  /**
   * 增加会话未读数
   */
  incrementUnreadCount(conversationId: string): void {
    const store = useMessageStore.getState();
    const conversation = store.getConversation(conversationId);
    if (!conversation) return;

    const prevUnreadCount = conversation.unread_count || 0;
    const newUnreadCount = prevUnreadCount + 1;

    // 创建新对象而不是直接修改，确保状态一致性
    const updatedConv: ConversationResponse = {
      ...conversation,
      unread_count: newUnreadCount,
    };
    
    store.updateConversation(updatedConv);

    const currentUnread = store.getUnreadCount();
    store.setUnreadCount(
      currentUnread.total + 1,
      currentUnread.system
    );
  }

  /**
   * 设置系统消息未读数
   */
  setSystemUnreadCount(count: number): void {
    const store = useMessageStore.getState();
    const currentUnread = store.getUnreadCount();
    store.setUnreadCount(currentUnread.total, count);
  }

  /**
   * 增加系统消息未读数
   */
  incrementSystemUnreadCount(): void {
    const store = useMessageStore.getState();
    const currentUnread = store.getUnreadCount();
    store.setUnreadCount(currentUnread.total, currentUnread.system + 1);
  }

  /**
   * 减少系统消息未读数
   */
  decrementSystemUnreadCount(count = 1): void {
    const store = useMessageStore.getState();
    const currentUnread = store.getUnreadCount();
    const newSystemCount = Math.max(0, currentUnread.system - count);
    store.setUnreadCount(currentUnread.total, newSystemCount);
  }
}