import { itGet } from "@/fetchHelpers";
import { useUserStore } from "@/stores/user";
import type { Notification } from "@/types";
import log from "loglevel";
import { defineStore } from "pinia";
import { ref, watch } from "vue";

type NotificationListData = {
  all_count: number;
  all_list: Notification[];
};

export const useNotificationsStore = defineStore("notifications", () => {
  const hasUnread = ref(false);
  const allCount = ref(0);

  async function loadNotifications(
    num_notifications: number,
    mark_as_read = true
  ): Promise<Notification[]> {
    const data = (await itGet(
      `/notifications/api/all_list/?max=${num_notifications}&mark_as_read=${mark_as_read}`
    )) as NotificationListData;
    allCount.value = data.all_count;
    await updateUnreadCount();
    return data.all_list;
  }

  async function updateUnreadCount() {
    const data = await itGet("/notifications/api/unread_count/");
    hasUnread.value = data.unread_count !== 0;
  }

  const userStore = useUserStore();
  let timerHandle: number | null = null;
  watch(userStore, () => {
    if (userStore.loggedIn && timerHandle === null) {
      log.debug("Notification polling started");
      updateUnreadCount();
      timerHandle = setInterval(
        async () => await updateUnreadCount(),
        30000
      ) as unknown as number;
    } else if (!userStore.loggedIn) {
      log.debug("Notification polling stopped");
      timerHandle = null;
    }
  });

  return { loadNotifications, hasUnread, allCount };
});
