import type { Notification } from './dto/notification'
import type { HydraCollection } from '~/utils/api'
import { fetchAllHydra } from '~/utils/api'

export function useNotificationService() {
    const api = useApi()

    async function getAll(): Promise<Notification[]> {
        // La ressource /notifications reste paginée côté back (volume non borné) :
        // on suit toutes les pages pour ne pas tronquer la liste à 30 éléments.
        return fetchAllHydra<Notification>(page =>
            api.get<HydraCollection<Notification>>('/notifications', { page }),
        )
    }

    async function markAsRead(id: number): Promise<void> {
        await api.patch(`/notifications/${id}`, { isRead: true }, {
            toast: false,
        })
    }

    async function markAllAsRead(): Promise<void> {
        await api.post('/notifications/mark-all-read', {}, {
            toast: false,
        })
    }

    async function getUnreadCount(): Promise<number> {
        const data = await api.get<{ count: number }>('/notifications/unread-count', {}, {
            toast: false,
        })
        return data.count
    }

    return { getAll, markAsRead, markAllAsRead, getUnreadCount }
}
