import { fetchUnreadMessagesCount } from '@api/chat';
import { storage, StoreType } from 'src/storage';
import { create } from 'zustand';

interface MessagesState {
  unreadMessagesCount: number;
  setUnreadMessagesCount: (count: number) => void;
  updateUnreadMessagesCount: () => Promise<void>;
}

export const useMessagesStore = create<MessagesState>((set) => ({
  unreadMessagesCount: (storage.get('unreadMessagesCount', StoreType.NUMBER) as number) ?? 0,
  setUnreadMessagesCount: (count: number) => set({ unreadMessagesCount: count }),
  updateUnreadMessagesCount: async () => {
    const token = storage.get('token', StoreType.STRING);
    if (token) {
      try {
        const messagesData = await fetchUnreadMessagesCount(token as string);
        if (messagesData && typeof messagesData.unread_conversations !== 'undefined') {
          set({ unreadMessagesCount: messagesData.unread_conversations });
          storage.set('unreadMessagesCount', messagesData.unread_conversations);
        }
      } catch (error) {
        console.error('Failed to fetch unread conversations count', error);
      }
    } else {
      set({ unreadMessagesCount: 0 });
      storage.set('unreadMessagesCount', 0);
    }
  }
}));
