import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { queryKeys } from '@/lib/query-keys'; import { notificationsApi } from '@/infrastructure/http/api/notifications/api'; import type { NotificationResponse } from '@archer/api-interface/schemas/customer-api/response'; import { type Notification, NotificationUrgency, NotificationMessageType, NotificationStatus, NotificationType, getNotificationUiProps, } from '@domain/entities'; function mapDtoToNotification(dto: NotificationResponse): Notification { const type = dto.type as NotificationType; const status = dto.status as NotificationStatus; const ui = getNotificationUiProps(type); return { ...dto, type, status, urgency: ui.urgency, messageType: ui.messageType, }; } export function useNotifications() { const queryClient = useQueryClient(); const { data: notifications = [] } = useQuery({ queryKey: queryKeys.notifications.all, queryFn: async () => { const dtos = await notificationsApi.list(); return dtos.map(mapDtoToNotification); }, refetchInterval: 30_000, refetchOnWindowFocus: true, }); const unreadCount = notifications.filter( (n) => n.status === NotificationStatus.UNREAD, ).length; const highestUrgency = getHighestUrgency(notifications); const messageTypes = getUnreadMessageTypes(notifications); const markReadMutation = useMutation({ mutationFn: (id: string) => notificationsApi.markRead(id), onSuccess: () => { queryClient.invalidateQueries({ queryKey: queryKeys.notifications.all }); }, }); const markAllReadMutation = useMutation({ mutationFn: () => notificationsApi.markAllRead(), onSuccess: () => { queryClient.invalidateQueries({ queryKey: queryKeys.notifications.all }); }, }); return { notifications, unreadCount, highestUrgency, messageTypes, markRead: markReadMutation.mutate, markAllRead: markAllReadMutation.mutate, }; } function getHighestUrgency(notifications: Notification[]): NotificationUrgency { const unread = notifications.filter((n) => n.status === NotificationStatus.UNREAD); if (unread.length === 0) return NotificationUrgency.LOW; if (unread.some((n) => n.urgency === NotificationUrgency.URGENT)) return NotificationUrgency.URGENT; if (unread.some((n) => n.urgency === NotificationUrgency.HIGH)) return NotificationUrgency.HIGH; if (unread.some((n) => n.urgency === NotificationUrgency.MEDIUM)) return NotificationUrgency.MEDIUM; return NotificationUrgency.LOW; } function getUnreadMessageTypes(notifications: Notification[]): NotificationMessageType[] { const unread = notifications.filter((n) => n.status === NotificationStatus.UNREAD); if (unread.length === 0) return [NotificationMessageType.INFO]; const types = Array.from(new Set(unread.map((n) => n.messageType))); return types.length > 0 ? types : [NotificationMessageType.INFO]; }