import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';

/// Bearer-token display name shown in the dashboard token list, in the form
/// `"Marianum Fulda App (Pixel 10)"`. Cached because device-info never
/// changes at runtime.
class DeviceTokenName {
  static const String _appName = 'Marianum Fulda App';

  static String? _cached;

  static Future<String> resolve() async {
    if (_cached != null) return _cached!;
    final device = await _deviceLabel();
    _cached = device.isEmpty ? _appName : '$_appName ($device)';
    return _cached!;
  }

  static Future<String> _deviceLabel() async {
    try {
      final info = DeviceInfoPlugin();
      if (Platform.isAndroid) {
        final android = await info.androidInfo;
        final model = android.model.trim();
        return model.isNotEmpty ? model : android.device.trim();
      }
      if (Platform.isIOS) {
        final ios = await info.iosInfo;
        // utsname.machine bleibt auch ohne user-zugewiesenen Gerätenamen
        // verfügbar; ios.name liefert auf iOS 16+ nur noch Generika.
        final machine = ios.utsname.machine.trim();
        if (machine.isNotEmpty) return machine;
        return ios.name.trim();
      }
    } catch (_) {
      // Device-Plugin nicht verfügbar (z.B. Tests).
    }
    return '';
  }
}
