import 'dart:developer';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:frontend_eccp_mobile/app/core/models/fcm_payload.dart';
import 'package:frontend_eccp_mobile/app/core/notification/fcm_route/notification_router.dart';
import 'package:frontend_eccp_mobile/app/core/notification/local_notification_service.dart';

class FcmNotificationHandler {
  FcmNotificationHandler._();

  static Future<void> handleForeground(RemoteMessage message) async {
    log('Foreground FCM: ${message.data}', name: 'FCM');

    final payload = FcmPayload.fromMessage({
      'notification': message.notification?.toMap(),
      'data': message.data,
    });

    if (payload.title != null && payload.body != null) {
      await LocalNotificationService.show(
        title: payload.title!,
        body: payload.body!,
        payload: payload.data,
      );
    }
  }

  static Future<void> handleOpenedApp(RemoteMessage message) async {
    log('Opened from FCM: ${message.data}', name: 'FCM');
    await NotificationRouter.handle(message.data);
  }

  static Future<void> handleLocalTap(String? payload) async {
    if (payload == null) return;
    await NotificationRouter.handleRaw(payload);
  }

  static Future<void> handleBackground(RemoteMessage message) async {
    log('Background FCM: ${message.data}', name: 'FCM');
    await NotificationRouter.handle(message.data);
  }
}
