import 'dart:async'; import '../../../core/api_gateway.dart'; import 'notification_bridge.dart'; import 'notification_models.dart'; /// Delivers live unanswered chat questions through the shared notification /// capability, without coupling chat event folding to platform notifications. class ChatQuestionNotices { ChatQuestionNotices({ required ApiGateway gateway, required this.canNotify, required this.activeChatSessionId, required this.sessionTitle, required this.openChat, required this.bridge, }) { _frames = gateway.frames.listen(_onEnvelope); } final bool Function() canNotify; final String? Function() activeChatSessionId; final Future Function(String sessionId) sessionTitle; final void Function(String sessionId) openChat; final NotificationBridge bridge; late final StreamSubscription _frames; bool _disposed = false; void _onEnvelope(JsonMap envelope) { if (envelope['type'] != 'chat_event') return; final event = envelope['chat_event']; if (event is! Map || event['kind'] != 'form') return; final sessionId = event['session_id']; final form = event['form']; if (sessionId is! String || sessionId.isEmpty || form is! Map || form['kind'] != 'question' || form['resolved'] == true || form['cancelled'] == true || form['id'] == null || !canNotify() || activeChatSessionId() == sessionId) { return; } unawaited(_show(sessionId, Map.from(form))); } Future _show(String sessionId, JsonMap form) async { String? session; try { session = await sessionTitle(sessionId); } catch (_) { // An unavailable session list is equivalent to an unknown session title. } if (_disposed || !canNotify() || activeChatSessionId() == sessionId) return; final title = (session ?? '').trim(); try { bridge.show( NotificationMessage( chatSessionId: sessionId, title: '${title.isEmpty ? 'Chat' : title} needs your answer', body: '${form['title'] ?? 'The agent asked a question.'}', tag: 'chat-question:${form['id']}', ), onTap: () => openChat(sessionId), ); } catch (_) { // Notification delivery must not interfere with the in-page question. } } void dispose() { _disposed = true; unawaited(_frames.cancel()); } }