import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

class DeviceUtils {
  static const String _deviceIdKey = 'deviceId';
  static const String _fcmTokenKey = 'fcmToken';

  static Future<String> ensureDeviceId(SharedPreferences prefs) async {
    final String? existing = prefs.getString(_deviceIdKey);
    if (existing != null && existing.isNotEmpty) {
      if (kDebugMode) print('[DEVICE] Using cached device ID: $existing');
      return existing;
    }
    try {
      final deviceInfo = DeviceInfoPlugin();
      final android = await deviceInfo.androidInfo;
      final String androidId = android.id;
      if (androidId.isNotEmpty) {
        await prefs.setString(_deviceIdKey, androidId);
        return androidId;
      } else {
        throw Exception('Android ID is empty');
      }
    } on PlatformException catch (e) {
      throw Exception('Failed to get device ID: ${e.message}');
    } catch (e) {
      throw Exception('Failed to get device ID: $e');
    }
  }

  static Future<String> ensureFcmToken(SharedPreferences prefs) async {
    try {
      final String? existing = prefs.getString(_fcmTokenKey);
      if (existing != null && existing.isNotEmpty) {
        return existing;
      }
      if (Firebase.apps.isEmpty) {
        try {
          await Firebase.initializeApp();
        } catch (_) {
          return '';
        }
      }
      final FirebaseMessaging messaging = FirebaseMessaging.instance;
      final NotificationSettings settings = await messaging.requestPermission(
        alert: true,
        badge: true,
        sound: true,
      );
      if (settings.authorizationStatus == AuthorizationStatus.authorized ||
          settings.authorizationStatus == AuthorizationStatus.provisional) {
        final String? token = await messaging.getToken();
        if (token != null && token.isNotEmpty) {
          await prefs.setString(_fcmTokenKey, token);
          return token;
        }
      }
    } catch (_) {}
    return '';
  }
}


