import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:slrpg_app/src/features/multiplayer/domain/entities/leaderboard_entry.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 records = await _api.pb.collection('leaderboard').getList(
        sort: '-level,-xp',
        perPage: 50,
      );

      return records.items.asMap().entries.map((entry) {
        final index = entry.key;
        final record = entry.value;
        final data = record.toJson();

        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');
    }
  }
}