import 'dart:math';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

/// A stable, anonymous per-install identifier for telemetry. Generated once on
/// first use (128 bits from a cryptographic RNG) and persisted in the secure
/// keystore, so a device stays a single row across password rotations and FCM
/// token refreshes — unlike the legacy device id which was derived from both.
/// Contains no user secret. A fresh install (or clearing app data) mints a new
/// id, which is intended: that is a new install.
class TelemetryDeviceId {
  static const String _key = 'telemetry_device_id';
  static const FlutterSecureStorage _storage = FlutterSecureStorage();

  static String? _cached;

  static Future<String> resolve() async {
    if (_cached != null) return _cached!;
    final existing = await _storage.read(key: _key);
    if (existing != null && existing.isNotEmpty) {
      _cached = existing;
      return existing;
    }
    final generated = _generate();
    await _storage.write(key: _key, value: generated);
    _cached = generated;
    return generated;
  }

  static String _generate() {
    final random = Random.secure();
    final bytes = List<int>.generate(16, (_) => random.nextInt(256));
    return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
  }
}
