import 'package:flutter_test/flutter_test.dart';

import 'package:lanebow/models/public_participant.dart';
import 'package:lanebow/models/public_team.dart';
import 'package:lanebow/utils/ranking_utils_public.dart';

void main() {
  group('PublicRankingUtils', () {
    test('caps score with handicap at 300 per game and ties rank', () {
      final p1 = PublicParticipant.fromJson({
        'participantId': '1',
        'name': 'A',
        'scores': [250, 280],
        'handicap': 0,
      }, gameCount: 2);
      final p2 = PublicParticipant.fromJson({
        'participantId': '2',
        'name': 'B',
        'scores': [295, 290],
        'handicap': 20, // 각 게임 합이 300 넘는 케이스 -> 캡
      }, gameCount: 2);

      final ranks = PublicRankingUtils.individualRanking([p1, p2]);
      // p1 totals: 250 + 280 = 530
      // p2 totals with cap: min(295+20,300)=300 + min(290+20,300)=300 => 600
      expect(ranks[0]['p'].participantId, '2');
      expect(ranks[0]['total'], 600);
      expect(ranks[0]['rank'], 1);
      expect(ranks[1]['p'].participantId, '1');
      expect(ranks[1]['total'], 530);
      expect(ranks[1]['rank'], 2);
    });

    test('tie produces 1,1,3 ranks', () {
      final p1 = PublicParticipant.fromJson({
        'participantId': '1', 'name': 'A', 'scores': [200], 'handicap': 0
      }, gameCount: 1);
      final p2 = PublicParticipant.fromJson({
        'participantId': '2', 'name': 'B', 'scores': [200], 'handicap': 0
      }, gameCount: 1);
      final p3 = PublicParticipant.fromJson({
        'participantId': '3', 'name': 'C', 'scores': [150], 'handicap': 0
      }, gameCount: 1);
      final ranks = PublicRankingUtils.individualRanking([p1, p2, p3]);
      expect(ranks[0]['total'], 200);
      expect(ranks[1]['total'], 200);
      expect(ranks[2]['total'], 150);
      expect(ranks[0]['rank'], 1);
      expect(ranks[1]['rank'], 1);
      expect(ranks[2]['rank'], 3);
    });

    test('team ranking sums member totals and team handicap', () {
      final team = PublicTeam.fromJson({
        'teamId': 'T1',
        'teamNumber': 1,
        'handicap': 5,
        'members': [
          {
            'participantId': '1',
            'name': 'A',
            'scores': [200, {'score': 150, 'handicap': 10}],
          },
          {
            'participantId': '2',
            'name': 'B',
            'scores': [100, 120],
          },
        ]
      }, gameCount: 2);
      final ranked = PublicRankingUtils.teamRanking([team]);
      // member1: 200 + min(150+10,300)=160 => 360
      // member2: 100 + 120 = 220
      // team total = 360 + 220 + teamHandicap(5) = 585
      expect(ranked[0]['total'], 585);
      expect(ranked[0]['rank'], 1);
    });
  });
}
