import { ref } from 'vue'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import {
  listNotifications,
  markAllNotificationsAsRead,
  markNotificationAsRead,
} from '../services/notification.service'
import type { NotificationItem } from '../types/notification.types'

const notifications = ref<NotificationItem[]>([])
const unreadCount = ref(0)
const loading = ref(false)
const error = ref<string | null>(null)

export function useNotifications() {
  async function fetchNotifications(perPage = 5) {
    loading.value = true
    error.value = null

    try {
      const response = await listNotifications({ per_page: perPage, page: 1 })
      notifications.value = response.data
      unreadCount.value = response.unread_count
    } catch (fetchError) {
      error.value = getApiErrorMessage(fetchError, 'Gagal memuatkan notifikasi.')
    } finally {
      loading.value = false
    }
  }

  async function markAsRead(id: string) {
    const notification = notifications.value.find((item) => item.id === id)
    if (!notification || notification.is_read) {
      return
    }

    try {
      await markNotificationAsRead(id)
      notification.is_read = true
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    } catch (markError) {
      error.value = getApiErrorMessage(markError, 'Gagal menandakan notifikasi sebagai dibaca.')
    }
  }

  async function markAllAsRead() {
    if (unreadCount.value === 0) {
      return
    }

    try {
      await markAllNotificationsAsRead()
      notifications.value = notifications.value.map((notification) => ({
        ...notification,
        is_read: true,
      }))
      unreadCount.value = 0
    } catch (markError) {
      error.value = getApiErrorMessage(markError, 'Gagal menandakan semua notifikasi sebagai dibaca.')
    }
  }

  return {
    notifications,
    unreadCount,
    loading,
    error,
    fetchNotifications,
    markAsRead,
    markAllAsRead,
  }
}
