// packages/service_api/lib/services/lobby_helper_service.dart
import 'dart:developer';
import 'package:service_api/service_api.dart';

/// [수정됨] 로비 화면의 중복 로직(랭킹, 레벨)을 처리하는 공통 서비스
class LobbyHelperService {
  final IdentityService _identityService;
  final PuzzleService _puzzleService;

  LobbyHelperService({
    required IdentityService identityService,
    required PuzzleService puzzleService,
  })  : _identityService = identityService,
        _puzzleService = puzzleService;

  /// (가벼움) 현재 게임의 최대 레벨만 로드
  Future<int> loadMaxLevel(String gameType) async {
    return await _identityService.getMaxUnlockedLevel(gameType: gameType);
  }

  /// [🔥 수정됨] (무거움) 랭킹 변동 이력(▲▼)을 반환 (levelIndex 추출기능 주입)
  Future<Map<int, (int, int)>> loadRankHistory<T extends GameDifficulty>({
    required String gameType,
    required String myName,
    required List<T> allLevels,
    required int Function(T level) getLevelIndex, // 👈 [수정] levelIndex 추출 함수
  }) async {
    try {
      final Map<int, int> oldRankMap =
          await _identityService.getLastSavedRankMap(gameType: gameType);

      List<Future<List<GameRankDto>>> rankFutures = [];
      for (final level in allLevels) {
        rankFutures.add(_puzzleService.fetchRanks(gameType, level.contextId));
      }

      final List<List<GameRankDto>> allRankResults =
          await Future.wait(rankFutures);
      Map<int, int> newRankMapForStorage = {};
      Map<int, (int, int)> newRankHistoryForState = {};

      for (int i = 0; i < allLevels.length; i++) {
        final level = allLevels[i];
        final currentRanks = allRankResults[i];

        // [🔥 수정] 주입받은 함수로 levelIndex를 안전하게 추출
        final int levelIndex = getLevelIndex(level);

        final int oldRank = oldRankMap[levelIndex] ?? 0;
        int currentRank = 0;
        int myRankIndex =
            currentRanks.indexWhere((r) => r.playerName == myName);
        if (myRankIndex != -1) {
          currentRank = myRankIndex + 1;
        }
        newRankMapForStorage[levelIndex] = currentRank;
        newRankHistoryForState[levelIndex] = (oldRank, currentRank);
      }

      await _identityService.saveLastRankMap(newRankMapForStorage,
          gameType: gameType);

      log("$gameType 랭킹 변동 확인 완료. (유저: $myName)");
      return newRankHistoryForState;
    } catch (e) {
      log("LobbyHelperService($gameType): 랭킹 확인 실패: $e");
      rethrow;
    }
  }
}