import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:slrpg_app/src/features/multiplayer/domain/entities/leaderboard_entry.dart';
import 'package:slrpg_app/src/shared/data/repositories/user_repository.dart';
import '../../../../shared/data/remote/api_client.dart';

final leaderboardRepositoryProvider = Provider((ref) {
  return LeaderboardRepository(ref.read(apiClientProvider));
});

class LeaderboardRepository {
  final ApiClient _api;

  LeaderboardRepository(this._api);

  Future<List<LeaderboardEntry>> getGlobalLeaderboard() async {
    try {
      final response = await _api.dio.get(
        '/api/collections/leaderboard/records',
        queryParameters: {
          'sort': '-level,-xp',
          'perPage': 50,
        },
      );

      final items = (response.data['items'] as List);

      return items.asMap().entries.map((entry) {
        final index = entry.key;
        final data = entry.value as Map<String, dynamic>;

        if (data['name'] == null || data['name'].toString().isEmpty) {
          data['name'] = 'Unknown Hero';
        }

        return LeaderboardEntry.fromJson(data).copyWith(rank: index + 1);
      }).toList();
    } catch (e) {
      throw Exception('Failed to load leaderboard: $e');
    }
  }
}
