import 'dart:async';
import 'dart:developer' as developer;

import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/foundation.dart';
import 'package:frontend_eccp_mobile/app/core/config/app_flavor.dart';

class CrashlyticsService {
  CrashlyticsService._();

  static FirebaseCrashlytics get _instance => FirebaseCrashlytics.instance;

  static Future<void> init() async {
    await _instance.setCrashlyticsCollectionEnabled(
      Flavor.isProd,
    );
    if (kDebugMode) return;

    FlutterError.onError = (FlutterErrorDetails details) async {
      await _instance.recordFlutterFatalError(details);
    };

    PlatformDispatcher.instance.onError = (error, stack) {
      unawaited(_instance.recordError(error, stack, fatal: true));
      return true;
    };
  }

  static Future<void> log(String message) async {
    if (kDebugMode) return;
    await _instance.log(message);
  }

  static Future<void> recordError(
    Object error,
    StackTrace stack, {
    String? reason,
    bool fatal = false,
    Map<String, dynamic>? context,
  }) async {
    if (kDebugMode) return;
    if (context != null) {
      context.forEach((key, value) async {
        await _instance.setCustomKey(key, value.toString());
      });
    }
    developer.log('CrashlyticsService.recordError: $reason');
    await _instance.recordError(
      error,
      stack,
      reason: reason,
      fatal: fatal,
    );
  }

  static Future<void> setUser({
    required String id,
    String? nrp,
    String? name,
  }) async {
    if (kDebugMode) return;
    await _instance.setUserIdentifier(id);
    if (nrp != null) {
      await _instance.setCustomKey('nrp', nrp);
    }
    if (name != null) {
      await _instance.setCustomKey('name', name);
    }
  }

  static Future<void> clearUser() async {
    if (kDebugMode) return;
    await _instance.setUserIdentifier('');
  }
}
