import {create} from 'zustand';

interface States {
  unreads: Record<string, number>;
  totalUnreadCount: number;
}

interface Actions {
  /**
   * Merge new unreads with the existing ones and update the total unread count.
   * @param newUnreads - New unreads to merge with the existing ones.
   */
  update: (unreads: Record<string, number>) => void;
  clear: () => void;
}

type Store = States & Actions;

export const unreadsStore = create<Store>(set => ({
  unreads: {},
  totalUnreadCount: 0,

  update: (newUnreads: Record<string, number>) => {
    set(state => {
      const oldUnreads = state.unreads;
      const unreads = {
        ...oldUnreads,
        ...newUnreads,
      };
      const totalUnreadCount = Object.values(unreads).reduce(
        (acc, count) => acc + count,
        0,
      );
      return {unreads, totalUnreadCount};
    });
  },
  clear: () => {
    set({unreads: {}, totalUnreadCount: 0});
  },
}));

export const useUnreadCount = (channel: string): number => {
  return unreadsStore(state => state.unreads[channel] ?? 0);
};

export const useTotalUnreadCount = (): number => {
  return unreadsStore(state => state.totalUnreadCount);
};
