import 'dart:convert';
import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:frontend_eccp_mobile/app/core/config/app_flavor.dart';
import 'package:frontend_eccp_mobile/app/core/config/app_update_config.dart';
import 'package:frontend_eccp_mobile/app/core/services/crashlytics_service.dart';

class RemoteConfigService {
  RemoteConfigService._();

  static final FirebaseRemoteConfig _rc = FirebaseRemoteConfig.instance;

  static Future<void> init() async {
    try {
      await _rc.setConfigSettings(
        RemoteConfigSettings(
          fetchTimeout: const Duration(seconds: 10),
          minimumFetchInterval: const Duration(minutes: 1),
        ),
      );

      await _rc.fetchAndActivate();
    } catch (e, s) {
      await CrashlyticsService.recordError(
        e,
        s,
        reason: 'RemoteConfig init failed',
      );
    }
  }

  static Future<AppUpdateConfig?> getUpdateConfig() async {
    try {
      final raw = _rc.getString(Flavor.name);
      if (raw.isEmpty) return null;

      final json = jsonDecode(raw) as Map<String, dynamic>;
      return AppUpdateConfig.fromJson(json);
    } catch (e, s) {
      await CrashlyticsService.recordError(
        e,
        s,
        reason: 'Invalid update config JSON',
      );
      return null;
    }
  }
}
