import 'dart:developer';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:hub/features/backend/index.dart';
import 'package:hub/features/storage/index.dart';

import 'package:hub/shared/utils/log_util.dart';

import 'notification_service.dart';

Future<void> handleMessage(RemoteMessage message) async {
  NotificationService.show(
      title: message.notification!.title!,
      body: message.notification!.body!,
      payload: Map<String, String>.from(message.data));
}

class FirebaseMessagingService {
  // Singleton instance
  static final FirebaseMessagingService _instance =
      FirebaseMessagingService._internal();

  // Factory constructor
  factory FirebaseMessagingService() => _instance;

  // Private constructor
  FirebaseMessagingService._internal();

  final _firebaseMessaging = FirebaseMessaging.instance;

  Future<void> initNotifications() async {
    await _firebaseMessaging.requestPermission();

    _firebaseMessaging.onTokenRefresh.listen((token) => updateDeviceToken);

    _firebaseMessaging.setAutoInitEnabled(false);
    _firebaseMessaging.pluginConstants;
  }

  static Future<String> getToken() async =>
      await FirebaseMessaging.instance.getToken() ?? '';

  Future<void> updateDeviceToken() async {
    try {
      final String? deviceToken = await _firebaseMessaging.getToken();

      if (deviceToken != null) {
        await StorageHelper().set(SecureStorageKey.token.value, deviceToken);
        final ApiCallResponse? response;

        response = await PhpGroup.updToken.call();

        if (response.jsonBody['error'] == false) {
          log('Token Atualizado com Sucesso!');
        } else {
          log('Falha ao Atualizar Token: ${response.jsonBody}');
        }
      } else {
        log('Falha ao Pegar Token do Firebase');
      }
    } catch (e, s) {
      LogUtil.requestAPIFailed("updToken.php", "", "Atualizar Token", e, s);
    }
  }
}
