import 'dart:io';
import 'package:comwell_key_app/base/base_cubit.dart';
import 'package:comwell_key_app/push_notifications/cubit/push_notification_state.dart';
import 'package:comwell_key_app/push_notifications/push_notification_repository.dart';
import 'package:comwell_key_app/utils/locator.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
class PushNotificationCubit extends BaseCubit<PushNotificationState> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
final PushNotificationRepository pushNotificationRepository =
locator<PushNotificationRepository>();
PushNotificationCubit() : super(PushNotificationState());
Future<void> initialize() async {
try {
await _firebaseMessaging.requestPermission();
// Ensure notifications show while app is in foreground on iOS
await _firebaseMessaging.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
await getFcmToken();
await registerPushTokenToSymplify();
// Keep tokens fresh
FirebaseMessaging.instance.onTokenRefresh.listen((String newToken) async {
String? refreshedApnsToken = state.apnsToken;
if (Platform.isIOS) {
// Re-read APNs token alongside refreshed FCM token
refreshedApnsToken = await _firebaseMessaging.getAPNSToken();
debugPrint('APNs Token (refreshed): $refreshedApnsToken');
}
debugPrint('FCM Token (refreshed): $newToken');
safeEmit(state.copyWith(fcmToken: newToken, apnsToken: refreshedApnsToken));
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
debugPrint('Message data: ${message.data}');
if (message.notification != null) {
safeEmit(state.copyWith(message: message.notification?.title));
}
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
safeEmit(state.copyWith(message: message.notification?.title));
});
} catch (e, st) {
logError(e, st);
safeEmit(state.copyWith(error: e.toString()));
}
}
Future<void> registerPushTokenToSymplify() async {
await pushNotificationRepository.registerDeviceAndProfile(state.fcmToken ?? '');
}
Future<void> getFcmToken() async {
String? apnsToken;
if (Platform.isIOS) {
// Give iOS time to register with APNs before requesting tokens
await Future<void>.delayed(const Duration(milliseconds: 500));
apnsToken = await _firebaseMessaging.getAPNSToken();
debugPrint('APNs Token: $apnsToken');
}
final String? fcmToken = await _firebaseMessaging.getToken();
debugPrint('FCM Token: $fcmToken');
safeEmit(state.copyWith(fcmToken: fcmToken, apnsToken: apnsToken));
}
Future<void> getApnsToken() async {
String? apnsToken;
if (Platform.isIOS) {
// Give iOS time to register with APNs before requesting tokens
await Future<void>.delayed(const Duration(milliseconds: 500));
apnsToken = await _firebaseMessaging.getAPNSToken();
debugPrint('APNs Token: $apnsToken');
}
safeEmit(state.copyWith(apnsToken: apnsToken));
}
}