import 'package:flutter/foundation.dart'; import 'package:onesignal_flutter/onesignal_flutter.dart'; /// OneSignal service for managing push notifications and external user ID. /// /// This service handles: /// - Setting external user ID after login (using phone number) /// - Restoring external user ID on app startup /// - Clearing external user ID on logout /// /// Usage: /// ```dart /// // After successful login /// await OneSignalService.login(phoneNumber); /// /// // On logout /// await OneSignalService.logout(); /// ``` class OneSignalService { OneSignalService._(); /// Login user to OneSignal by setting external user ID. /// /// This associates the device with the user's phone number, /// allowing targeted push notifications to specific users. /// /// [phoneNumber] - The user's phone number (used as external ID) static Future login(String phoneNumber) async { try { // Set external user ID for targeting await OneSignal.login(phoneNumber); debugPrint('🔔 OneSignal: login - external_id set to $phoneNumber'); } catch (e) { debugPrint('🔔 OneSignal error: Failed to set external user ID - $e'); } } /// Logout user from OneSignal by removing external user ID. /// /// This disassociates the device from the user, /// so notifications won't be sent to this specific user anymore. static Future logout() async { try { await OneSignal.logout(); debugPrint('🔔 OneSignal: logout - external_id cleared'); } catch (e) { debugPrint('🔔 OneSignal error: Failed to clear external user ID - $e'); } } /// Add a tag to the user for segmentation. /// /// Tags can be used to segment users for targeted notifications. /// Example: tier = "diamond", role = "contractor" static Future setTag(String key, String value) async { try { await OneSignal.User.addTagWithKey(key, value); debugPrint('🔔 OneSignal: tag set - $key: $value'); } catch (e) { debugPrint('🔔 OneSignal error: Failed to set tag - $e'); } } /// Add multiple tags at once. static Future setTags(Map tags) async { try { await OneSignal.User.addTags(tags); debugPrint('🔔 OneSignal: tags set - $tags'); } catch (e) { debugPrint('🔔 OneSignal error: Failed to set tags - $e'); } } /// Remove a tag from the user. static Future removeTag(String key) async { try { await OneSignal.User.removeTag(key); debugPrint('🔔 OneSignal: tag removed - $key'); } catch (e) { debugPrint('🔔 OneSignal error: Failed to remove tag - $e'); } } /// Get the OneSignal subscription ID (player ID). /// /// This is the device-specific ID used by OneSignal. static String? get subscriptionId => OneSignal.User.pushSubscription.id; /// Check if push notifications are enabled. static bool get isPushEnabled => OneSignal.User.pushSubscription.optedIn ?? false; }