import type { NotificationResponseDto } from '@/api/generated/models' import { createServiceError, errorResult, handleServiceError, type ServiceCallOptions, type ServiceResult, shouldBubbleErrorToParent, successResult, } from '@/services/errorHandler' import { unwrapApiData } from '@/services/apiResponse' import { getNotifications } from '@/api/generated/notifications/notifications' import { parseRemittanceList } from '@/helpers/listResponse' import { texts } from '@/texts' export type InAppNotification = NotificationResponseDto const notificationsApi = getNotifications() export const LIST_NOTIFICATIONS = async (options?: ServiceCallOptions): Promise> => { try { const res = await notificationsApi.notificationsControllerListMine({ page: 1, pageSize: 30, sort: '-createdAt' }) const parsed = parseRemittanceList(res.data, 'items') return successResult({ items: parsed.items }) } catch (error) { const normalizedError = handleServiceError(error, options) if (shouldBubbleErrorToParent(options)) { throw normalizedError } return errorResult(normalizedError) } } export const GET_UNREAD_NOTIFICATION_COUNT = async (options?: ServiceCallOptions): Promise> => { try { const res = await notificationsApi.notificationsControllerUnreadCount() if (!res.data.success) throw createServiceError(res.data.message) const payload = unwrapApiData(res.data) const totalUnread = Number(payload?.totalUnread ?? 0) return successResult({ totalUnread: Number.isFinite(totalUnread) ? totalUnread : 0 }) } catch (error) { const normalizedError = handleServiceError(error, options) if (shouldBubbleErrorToParent(options)) { throw normalizedError } return errorResult(normalizedError) } } export const MARK_NOTIFICATION_READ = async ( notificationId: string, options?: ServiceCallOptions ): Promise> => { try { const res = await notificationsApi.notificationsControllerMarkAsRead(notificationId) if (!res.data.success) throw createServiceError(res.data.message) const payload = unwrapApiData(res.data) if (!payload?.id) { throw createServiceError(texts.common.invalidServerResponse) } return successResult(payload) } catch (error) { const normalizedError = handleServiceError(error, options) if (shouldBubbleErrorToParent(options)) { throw normalizedError } return errorResult(normalizedError) } } export const countUnreadNotifications = (items: InAppNotification[]): number => items.filter((item) => !item.readAt).length