import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import '../api/api_client.dart'; /// Handles FCM token registration and foreground message display. class FcmService { static final FirebaseMessaging _messaging = FirebaseMessaging.instance; /// Request permission and register/refresh the FCM token with the backend. static Future init() async { final settings = await _messaging.requestPermission( alert: true, badge: true, sound: true, ); if (settings.authorizationStatus == AuthorizationStatus.denied) return; final token = await _messaging.getToken(); if (token != null) { await _sendTokenToBackend(token); } // Re-register when token refreshes _messaging.onTokenRefresh.listen(_sendTokenToBackend); // Foreground messages — just log for now; app uses in-app bell for real-time FirebaseMessaging.onMessage.listen((message) { debugPrint('[FCM] foreground: ${message.notification?.title}'); }); } static Future _sendTokenToBackend(String token) async { try { await apiDio.patch('/users/me/profile', data: {'push_token': token}); } catch (e) { debugPrint('[FCM] token upload error: $e'); } } /// Clear push token on logout so stale tokens don't receive notifications. static Future clearToken() async { try { await apiDio.patch('/users/me/profile', data: {'push_token': null}); await _messaging.deleteToken(); } catch (e) { debugPrint('[FCM] clear token error: $e'); } } }