class Score {
  final String id;
  final String memberId;
  final String eventId;
  final String clubId;
  final String? participantId; // 참가자 ID (백엔드 EventScore 필드)
  final List<int> frames;
  final int totalScore;
  final int? handicap; // 핸디캡 추가
  final int? gameNumber; // 게임 번호 (백엔드 EventScore 필드)
  final DateTime date;
  final String? notes;
  final String? participantName;

  Score({
    required this.id,
    required this.memberId,
    required this.eventId,
    required this.clubId,
    this.participantId,
    required this.frames,
    required this.totalScore,
    this.handicap,
    this.gameNumber,
    required this.date,
    this.notes,
    this.participantName,
  });
  
  // 핸디캡 포함 총점 계산
  int get totalWithHandicap => totalScore + (handicap ?? 0);

  factory Score.fromJson(Map<String, dynamic> json) {
    return Score(
      id: json['id']?.toString() ?? '',
      memberId: json['memberId']?.toString() ?? '',
      eventId: json['eventId']?.toString() ?? '',
      clubId: json['clubId']?.toString() ?? '',
      participantId: json['participantId']?.toString(),
      frames: json['frames'] != null ? List<int>.from(json['frames']) : [],
      // 서버는 base 점수를 'score'로, 합계(핸디 포함)를 'totalScore'로 반환할 수 있음.
      // 앱 내부에서는 base 점수를 totalScore 필드에 저장하여 일관되게 사용하고,
      // 핸디 포함 합계는 getter(totalWithHandicap)로 계산한다.
      totalScore: (json['score'] ?? json['totalScore']) ?? 0,
      handicap: json['handicap'],
      gameNumber: () {
        final v = json['gameNumber'];
        if (v == null) return null;
        if (v is int) return v;
        return int.tryParse(v.toString());
      }(),
      date: json['date'] != null ? DateTime.parse(json['date'].toString()) : DateTime.now(),
      notes: json['notes']?.toString(),
      participantName: json['participantName']?.toString(),
    );
  }

  Map<String, dynamic> toJson() {
    final map = {
      'id': id,
      'memberId': memberId,
      'eventId': eventId,
      'clubId': clubId,
      'frames': frames,
      'totalScore': totalScore,
      'handicap': handicap,
      'gameNumber': gameNumber,
      'date': date.toIso8601String(),
      'notes': notes,
      'participantName': participantName,
    };
    if (participantId != null) {
      map['participantId'] = participantId;
    }
    return map;
  }
}

class ScoreStatistics {
  final double average;
  final int highScore;
  final int lowScore;
  final int gamesPlayed;
  final Map<String, dynamic>? additionalStats;

  ScoreStatistics({
    required this.average,
    required this.highScore,
    required this.lowScore,
    required this.gamesPlayed,
    this.additionalStats,
  });

  factory ScoreStatistics.fromJson(Map<String, dynamic> json) {
    return ScoreStatistics(
      average: json['average'] != null ? (json['average'] is int ? (json['average'] as int).toDouble() : json['average'].toDouble()) : 0.0,
      highScore: json['highScore'] ?? 0,
      lowScore: json['lowScore'] ?? 0,
      gamesPlayed: json['gamesPlayed'] ?? 0,
      additionalStats: json['additionalStats'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'average': average,
      'highScore': highScore,
      'lowScore': lowScore,
      'gamesPlayed': gamesPlayed,
      'additionalStats': additionalStats,
    };
  }
}
