import 'dart:developer';
import 'package:firebase_messaging/firebase_messaging.dart';

class FcmTokenManager {
  FcmTokenManager._();

  static final FirebaseMessaging _fcm = FirebaseMessaging.instance;

  static Future<void> waitForAPNSToken() async {
    String? apnsToken;

    while (apnsToken == null) {
      await Future<dynamic>.delayed(const Duration(milliseconds: 500));
      apnsToken = await _fcm.getAPNSToken();
    }

    log('APNS Token ready: $apnsToken', name: 'FCM');
  }

  static Future<String?> getToken() async {
    try {
      await _fcm.requestPermission();

      // await waitForAPNSToken();

      final token = await _fcm.getToken();
      log('FCM Token: $token', name: 'FCM');

      return token;
    } catch (e) {
      log('Get token error: $e', name: 'FCM');
      return null;
    }
  }

  static Future<void> deleteToken() async {
    try {
      await _fcm.deleteToken();
      log('FCM Token deleted', name: 'FCM');
    } catch (e) {
      log('Delete token error: $e', name: 'FCM');
    }
  }

  static void listenRefresh(void Function(String token) onRefresh) {
    FirebaseMessaging.instance.onTokenRefresh.listen((token) {
      log('FCM Token refreshed: $token', name: 'FCM');
      onRefresh(token);
    });
  }
}
