import 'package:firebase_storage/firebase_storage.dart';

typedef OnAvatarTap = void Function();

final Map<String, String> _avatarUrlCache = {};

void clearAvatarCache([String? userId]) {
  if (userId != null) {
    _avatarUrlCache.remove(userId);
  } else {
    _avatarUrlCache.clear();
  }
}

String? getCachedAvatarUrl(String userId) => _avatarUrlCache[userId];

void cacheAvatarUrl(String userId, String url) {
  if (url.isNotEmpty) _avatarUrlCache[userId] = url;
}

String cacheBustedAvatarUrl(String url, Object version) {
  if (url.isEmpty) return url;
  final uri = Uri.tryParse(url);
  if (uri == null) {
    final separator = url.contains('?') ? '&' : '?';
    return '$url${separator}v=$version';
  }
  final query = Map<String, String>.from(uri.queryParameters)
    ..['v'] = version.toString();
  return uri.replace(queryParameters: query).toString();
}

/// Resolves the avatar download URL for [userId].
/// Uses the in-memory cache so repeated calls are instant.
Future<String> resolveAvatarUrl(String userId) async {
  final cached = _avatarUrlCache[userId];
  if (cached != null && cached.isNotEmpty) return cached;
  try {
    final ref = FirebaseStorage.instance
        .ref()
        .child('users')
        .child(userId)
        .child('avatar')
        .child('thumb.jpg');
    final url = await ref.getDownloadURL();
    if (url.isNotEmpty) _avatarUrlCache[userId] = url;
    return url;
  } catch (_) {
    return '';
  }
}
