import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:lanebow/models/event_model.dart';
import 'package:lanebow/models/participant_model.dart';
import 'package:lanebow/models/team_model.dart';
import 'package:lanebow/screens/club/event_details_screen.dart';
import 'package:lanebow/services/event_service.dart';
import 'package:lanebow/services/member_service.dart';
import 'package:provider/provider.dart';

void main() {
  setUp(() {
    // 테스트 모드 활성화: 실제 _loadEventDetails 호출을 건너뛰게 함
    EventDetailsScreen.testMode = true;
  });

  tearDown(() {
    EventDetailsScreen.testMode = false;
  });

  group('팀 저장 서버 포맷 매핑 테스트', () {
    testWidgets('buildServerTeamsForSave: memberIds -> participant.id 매핑 및 order 부여', (tester) async {
      // given
      final event = Event(
        id: 'ev1',
        clubId: 'c1',
        title: '테스트',
        type: 'team',
        status: 'draft',
        startDate: DateTime.now(),
        isActive: true,
      );

      final participants = <Participant>[
        Participant(id: 'p1', eventId: 'ev1', memberId: 'm1', name: 'A'),
        Participant(id: 'p2', eventId: 'ev1', memberId: 'm2', name: 'B'),
        Participant(id: 'p3', eventId: 'ev1', memberId: 'm3', name: 'C'),
      ];

      final teams = <Team>[
        Team(id: 't1', eventId: 'ev1', name: 'A', memberIds: ['m1', 'm3']),
        Team(id: 't2', eventId: 'ev1', name: 'B', memberIds: ['m2']),
      ];

      await tester.pumpWidget(
        MultiProvider(
          providers: [
            ChangeNotifierProvider<EventService>(create: (_) => EventService()),
            ChangeNotifierProvider<MemberService>(create: (_) => MemberService()),
          ],
          child: MaterialApp(
            home: EventDetailsScreen(event: event),
          ),
        ),
      );
      await tester.pumpAndSettle();

      // when: State를 가져와 helper 호출
      final state = tester.state(find.byType(EventDetailsScreen));
      // private 타입이므로 dynamic으로 메서드 호출
      final dynamic dyn = state;
      final result = dyn.buildServerTeamsForSave(teams, participants) as List<Map<String, dynamic>>;

      // then
      expect(result.length, 2);
      // team 1
      expect(result[0]['teamNumber'], 1);
      expect(result[0]['handicap'], 0);
      final members1 = (result[0]['members'] as List).cast<Map<String, dynamic>>();
      expect(members1.length, 2);
      expect(members1[0]['id'], 'p1');
      expect(members1[0]['order'], 1);
      expect(members1[1]['id'], 'p3');
      expect(members1[1]['order'], 2);
      // team 2
      expect(result[1]['teamNumber'], 2);
      final members2 = (result[1]['members'] as List).cast<Map<String, dynamic>>();
      expect(members2.length, 1);
      expect(members2[0]['id'], 'p2');
      expect(members2[0]['order'], 1);
    });
  });
}
