import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  getNotificationCount,
  getNotifications,
  markAllNotificationsRead,
  markNotificationRead,
  type NotificationEntry,
} from '@/api/client'

export const useNotificationsStore = defineStore('notifications', () => {
  const count = ref(0)
  const items = ref<NotificationEntry[]>([])

  async function fetchCount() {
    try {
      count.value = await getNotificationCount()
    } catch {
      // silently ignore — polling failure shouldn't surface to user
    }
  }

  async function fetchAll() {
    try {
      items.value = await getNotifications(false)
      count.value = items.value.length
    } catch {
      //
    }
  }

  async function markRead(id: number) {
    await markNotificationRead(id)
    items.value = items.value.filter(n => n.id !== id)
    count.value = Math.max(0, count.value - 1)
  }

  async function markAll() {
    await markAllNotificationsRead()
    items.value = []
    count.value = 0
  }

  return { count, items, fetchCount, fetchAll, markRead, markAll }
})
