import Foundation import Observation import DevPlaceSwiftSDK extension NotificationsView { @Observable final class ViewModel { let api: DevPlaceApi var notifications: Notifications? var alertMessage: AlertMessage = .none() var isLoadingMore = false init(api: DevPlaceApi) { self.api = api } struct Row: Identifiable { let id: String let notification: DevPlaceSwiftSDK.Notification let count: Int let isUnread: Bool } var groups: [NotificationGroup] { notifications?.groups ?? [] } func rows(in group: NotificationGroup) -> [Row] { if notifications?.grouping == true { return group.eventEntries.map { eventGroup in Row( id: eventGroup.id, notification: eventGroup.latest, count: eventGroup.count, isUnread: eventGroup.unread, ) } } return group.entries.map { entry in Row( id: entry.id, notification: entry, count: 1, isUnread: !entry.data.read, ) } } func load() async { guard AppState.shared.isLoggedIn else { notifications = nil return } do { notifications = try await api.notifications() } catch { alertMessage = .presentedError(error) } } func refresh() async { guard AppState.shared.isLoggedIn else { notifications = nil return } do { notifications = try await api.notifications() await refreshUnreadCount() } catch { alertMessage = .presentedError(error) } } func refreshUnreadCount() async { await AppState.shared.loadUnreadNotificationCount(api: api) } func loadMore() async { guard !isLoadingMore, let cursor = notifications?.nextCursor else { return } isLoadingMore = true defer { isLoadingMore = false } do { let older = try await api.notifications(before: cursor) if let existing = notifications { notifications = merged(existing, with: older) } else { notifications = older } } catch { alertMessage = .presentedError(error) } } func open(notification: DevPlaceSwiftSDK.Notification) async -> NotificationRoute? { do { let result = try await api.openNotification(uid: notification.data.id) let route = route(for: notification, redirect: result.redirect) await load() await refreshUnreadCount() return route } catch { alertMessage = .presentedError(error) return nil } } private func route(for notification: DevPlaceSwiftSDK.Notification, redirect: String) -> NotificationRoute? { if notification.data.type == .message, let otherUser = notification.actor { return .conversation(otherUser) } if notification.data.type == .badge || notification.data.type == .level { return .ownProfile } return NotificationRoute(redirect: redirect) } func markRead(uid: String) async { notifications = applyingRead(uids: [uid]) do { try await api.markNotificationRead(uid: uid) await refreshUnreadCount() } catch { alertMessage = .presentedError(error) await load() } } func markAllRead() async { let entryUids = groups.flatMap { $0.entries }.map { $0.data.id } let latestUids = groups.flatMap { $0.eventEntries }.map { $0.latest.data.id } let allUids = Set(entryUids + latestUids) notifications = applyingRead(uids: allUids) do { try await api.markAllNotificationsRead() await refreshUnreadCount() } catch { alertMessage = .presentedError(error) await load() } } private func merged(_ existing: Notifications, with older: Notifications) -> Notifications { var groups = existing.groups for group in older.groups { if let index = groups.firstIndex(where: { $0.label == group.label }) { groups[index] = NotificationGroup( label: group.label, entries: groups[index].entries + group.entries, eventEntries: mergedEventEntries(groups[index].eventEntries, with: group.eventEntries), ) } else { groups.append(group) } } return deduplicated( Notifications( groups: groups, nextCursor: older.nextCursor, grouping: existing.grouping, ) ) } private func mergedEventEntries( _ existing: [NotificationEventGroup], with older: [NotificationEventGroup], ) -> [NotificationEventGroup] { var merged = existing for eventGroup in older { if let index = merged.firstIndex(where: { $0.key == eventGroup.key }) { merged[index] = combined(merged[index], eventGroup) } else { merged.append(eventGroup) } } return merged } private func combined(_ newer: NotificationEventGroup, _ older: NotificationEventGroup) -> NotificationEventGroup { var actors = newer.actors for actor in older.actors where actors.count < 3 && !actors.contains(where: { $0.id == actor.id }) { actors.append(actor) } return NotificationEventGroup( key: newer.key, count: newer.count + older.count, unread: newer.unread || older.unread, actors: actors, latest: newer.latest, ) } private func deduplicated(_ notifications: Notifications) -> Notifications { var seenIds: Set = [] var duplicateIds: [String] = [] let groups = notifications.groups.map { group in let uniqueEntries = group.entries.filter { entry in let id = entry.data.id guard seenIds.insert(id).inserted else { duplicateIds.append(id) return false } return true } return NotificationGroup( label: group.label, entries: uniqueEntries, eventEntries: group.eventEntries, ) } if !duplicateIds.isEmpty { dlog("Dropped duplicate notification IDs while loading more: \(duplicateIds.joined(separator: ", "))") } return Notifications( groups: groups.filter { !$0.entries.isEmpty || !$0.eventEntries.isEmpty }, nextCursor: notifications.nextCursor, grouping: notifications.grouping, ) } private func applyingRead(uids: Set) -> Notifications? { guard let notifications else { return nil } let groups = notifications.groups.map { group in NotificationGroup( label: group.label, entries: group.entries.map { entry in markedRead(entry, uids: uids) }, eventEntries: group.eventEntries.map { eventGroup in guard uids.contains(eventGroup.latest.data.id) else { return eventGroup } return NotificationEventGroup( key: eventGroup.key, count: eventGroup.count, unread: false, actors: eventGroup.actors, latest: markedRead(eventGroup.latest, uids: uids), ) }, ) } return Notifications( groups: groups, nextCursor: notifications.nextCursor, grouping: notifications.grouping, ) } private func markedRead(_ notification: DevPlaceSwiftSDK.Notification, uids: Set) -> DevPlaceSwiftSDK.Notification { guard uids.contains(notification.data.id), !notification.data.read else { return notification } return DevPlaceSwiftSDK.Notification( data: .init( id: notification.data.id, type: notification.data.type, message: notification.data.message, read: true, relatedId: notification.data.relatedId, targetUrl: notification.data.targetUrl, createdAt: notification.data.createdAt, ), actor: notification.actor, ) } } }