import { fetchFriendsNotification } from '@api/friends';
import { storage, StoreType } from 'src/storage';
import { create } from 'zustand';

interface FriendsNotificationState {
  isNotificationActive: number;
  setIsNotificationActive: (active: number) => void;
  updateNotificationStatus: () => Promise<void>;
}

export const useFriendsNotificationsStore = create<FriendsNotificationState>((set) => ({
  isNotificationActive: (storage.get('friendsNotification', StoreType.NUMBER) as number) ?? 0,
  setIsNotificationActive: (active: number) => set({ isNotificationActive: active }),
  updateNotificationStatus: async () => {
    const token = storage.get('token', StoreType.STRING);
    if (token) {
      try {
        const data = await fetchFriendsNotification(token as string);
        const count = data && data.count;

        if (typeof count === 'number') {
          set({ isNotificationActive: count });
          storage.set('friendsNotification', count);
        }
      } catch (error) {
        console.error('Failed to fetch friends notification status', error);
      }
    } else {
      set({ isNotificationActive: 0 });
      storage.set('friendsNotification', 0);
    }
  }
}));
