// IndexedDB 数据库工具类
class ChatDB {
  constructor() {
    this.dbName = 'ChatApp';
    this.version = 1;
    this.db = null;
  }

  // 清空未读消息
  async clearUnreadCount(friendId) {
    const transaction = this.db.transaction(['friends'], 'readwrite');
    const store = transaction.objectStore('friends');

    const request = store.get(friendId);

    return new Promise((resolve, reject) => {
      request.onsuccess = () => {
        const friend = request.result;
        if (friend) {
          friend.unreadCount = 0;
          store.put(friend);
        }
        resolve();
      };
      request.onerror = () => reject(request.error);
    });
  }

  // 获取聊天记录
  async getChatHistory(currentUserId, friendId) {
    const transaction = this.db.transaction(['messages'], 'readonly');
    const store = transaction.objectStore('messages');
    const index = store.index('chatKey');

    const chatKey = `${currentUserId}_${friendId}`;
    const request = index.getAll(chatKey);

    return new Promise((resolve, reject) => {
      request.onsuccess = () => resolve(request.result || []);
      request.onerror = () => reject(request.error);
    });
  }

  // 获取好友列表
  async getFriends(currentUserId) {
    const transaction = this.db.transaction(['friends'], 'readonly');
    const store = transaction.objectStore('friends');
    const index = store.index('userId');

    const request = index.getAll(currentUserId);

    return new Promise((resolve, reject) => {
      request.onsuccess = () => resolve(request.result || []);
      request.onerror = () => reject(request.error);
    });
  }

  async init() {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, this.version);

      request.onerror = () => reject(request.error);
      request.onsuccess = () => {
        this.db = request.result;
        resolve(this.db);
      };

      request.onupgradeneeded = (event) => {
        const db = event.target.result;

        // 创建聊天记录表
        if (!db.objectStoreNames.contains('messages')) {
          const messageStore = db.createObjectStore('messages', {
            keyPath: 'id',
            autoIncrement: true,
          });
          messageStore.createIndex('chatKey', 'chatKey', { unique: false });
          messageStore.createIndex('timestamp', 'timestamp', { unique: false });
        }

        // 创建用户表
        if (!db.objectStoreNames.contains('users')) {
          const userStore = db.createObjectStore('users', { keyPath: 'id' });
        }

        // 创建好友表
        if (!db.objectStoreNames.contains('friends')) {
          const friendStore = db.createObjectStore('friends', {
            keyPath: 'id',
          });
          friendStore.createIndex('userId', 'userId', { unique: false });
        }
      };
    });
  }

  // 保存好友信息
  async saveFriend(friend, currentUserId) {
    const transaction = this.db.transaction(['friends'], 'readwrite');
    const store = transaction.objectStore('friends');

    const friendData = {
      ...friend,
      userId: currentUserId,
      updatedAt: Date.now(),
    };

    return store.put(friendData);
  }

  // 保存消息
  async saveMessage(message, currentUserId, friendId) {
    const transaction = this.db.transaction(['messages'], 'readwrite');
    const store = transaction.objectStore('messages');

    const messageData = {
      ...message,
      chatKey: `${currentUserId}_${friendId}`,
      timestamp: Date.now(),
    };

    return store.add(messageData);
  }

  // 更新好友最后消息
  async updateFriendLastMessage(
    friendId,
    currentUserId,
    lastMessage,
    unreadCount = 0,
  ) {
    const transaction = this.db.transaction(['friends'], 'readwrite');
    const store = transaction.objectStore('friends');

    const request = store.get(friendId);

    return new Promise((resolve, reject) => {
      request.onsuccess = () => {
        const friend = request.result;
        if (friend) {
          friend.lastMessage = lastMessage;
          friend.unreadCount = unreadCount;
          friend.updatedAt = Date.now();
          store.put(friend);
        }
        resolve();
      };
      request.onerror = () => reject(request.error);
    });
  }
}

export const chatDB = new ChatDB();
