// lib/models/game_rank_dto.dart

class GameRankDto {
  final String playerName;
  final int primaryScore;   // 시간 (초)
  final int? secondaryScore; // 점수 (저장된 값, 예: 0~4)

  GameRankDto({
    required this.playerName, 
    required this.primaryScore, 
    this.secondaryScore
  });

  factory GameRankDto.fromJson(Map<String, dynamic> json) {
    // [🔥 수정] playerName에 Null check 추가
    // [🔥 수정] primaryScore에 Null check 및 안전한 toInt() 추가
    return GameRankDto(
      playerName: json['playerName'] ?? 'Unknown', 
      primaryScore: (json['primaryScore'] as num?)?.toInt() ?? 0, 
      secondaryScore: (json['secondaryScore'] as num?)?.toInt(),
    );
  }
}

// 🔽 [신규 추가] 나의 랭킹 + 순위(숫자)를 담는 DTO
class GameRankWithRankNumber {
  final GameRankDto rankData;
  final int rankNumber;

  GameRankWithRankNumber({
    required this.rankData,
    required this.rankNumber,
  });

  factory GameRankWithRankNumber.fromJson(Map<String, dynamic> json) {
    return GameRankWithRankNumber(
      rankData: GameRankDto.fromJson(json['rankData']),
      // [🔥 수정] rankNumber에 Null check 및 안전한 toInt() 추가
      rankNumber: (json['rankNumber'] as num?)?.toInt() ?? 0,
    );
  }
}

// 🔽 [신규 추가] 랭킹 등록 시 서버가 반환하는 최종 DTO
class RankSubmissionResult {
  final List<GameRankDto> topRanks; // 상위 10개 랭킹
  final GameRankWithRankNumber? myRank; // 나의 랭킹 정보 (순위 포함)

  RankSubmissionResult({
    required this.topRanks,
    this.myRank,
  });

  factory RankSubmissionResult.fromJson(Map<String, dynamic> json) {
    // topRanks 파싱
    final List<dynamic> topRanksJson = json['topRanks'] ?? [];
    final List<GameRankDto> topRanksList = topRanksJson
        .map((item) => GameRankDto.fromJson(item))
        .toList();

    // myRank 파싱 (null일 수 있음)
    final Map<String, dynamic>? myRankJson = json['myRank'];
    final GameRankWithRankNumber? myRankData =
        myRankJson != null ? GameRankWithRankNumber.fromJson(myRankJson) : null;

    return RankSubmissionResult(
      topRanks: topRanksList,
      myRank: myRankData,
    );
  }
}