import 'dart:developer';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:frontend_eccp_mobile/app/core/notification/fcm_background_handler.dart';
import 'package:frontend_eccp_mobile/app/core/notification/fcm_notification_handler.dart';
import 'package:frontend_eccp_mobile/app/core/notification/fcm_token_manager.dart';
import 'package:frontend_eccp_mobile/app/core/notification/local_notification_service.dart';
import 'package:frontend_eccp_mobile/app/core/notification/notification_intent_store.dart';

class FcmService {
  FcmService._();

  static final FirebaseMessaging _fcm = FirebaseMessaging.instance;

  static Future<void> init() async {
    await _fcm.requestPermission();

    await LocalNotificationService.init(
      onSelectNotification: FcmNotificationHandler.handleLocalTap,
    );

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

    FcmTokenManager.listenRefresh((token) {
      log('FCM Token refreshed: $token', name: 'FCM');
    });

    FirebaseMessaging.onMessage.listen(
      FcmNotificationHandler.handleForeground,
    );

    FirebaseMessaging.onMessageOpenedApp.listen(
      FcmNotificationHandler.handleOpenedApp,
    );
    final initialMessage = await _fcm.getInitialMessage();
    if (initialMessage != null) {
      NotificationIntentStore.pending = initialMessage.data;
    }

    FirebaseMessaging.onBackgroundMessage(
      firebaseMessagingBackgroundHandler,
    );
  }
}
