import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:lanebow/screens/public_event/public_event_entry_screen.dart';
import 'package:lanebow/screens/public_event/public_event_screen.dart';
import 'package:lanebow/services/public_event_service.dart';

DioException dio401(String path) => DioException(
  requestOptions: RequestOptions(path: path),
  response: Response(requestOptions: RequestOptions(path: path), statusCode: 401),
  type: DioExceptionType.badResponse,
);

class StubFetch401Service extends PublicEventService {
  @override
  Future<Map<String, dynamic>> fetchEvent(String publicHash) async {
    throw dio401('/api/public/' + publicHash);
  }
}

class StubUpdate401Service extends PublicEventService {
  @override
  Future<Map<String, dynamic>> fetchEvent(String publicHash) async {
    return {
      'event': {'id': 'E1', 'title': '테스트 이벤트', 'gameCount': 3, 'status': 'active'},
      'participants': [
        {
          'participantId': 'p1',
          'name': 'Kim',
          'scores': [100, null, null],
          'handicap': 0,
        },
      ],
      'teams': [],
    };
  }

  @override
  Future<void> updateScore(String publicHash, {required String participantId, required int gameNumber, required int score, int? handicap, dynamic teamNumber}) async {
    throw dio401('/api/public/' + publicHash + '/score');
  }
}

void main() {
  testWidgets('401 on fetchEvent navigates to entry screen', (tester) async {
    await tester.pumpWidget(MaterialApp(
      home: PublicEventScreen(publicHash: 'abc', service: StubFetch401Service()),
    ));

    await tester.pumpAndSettle();
    expect(find.byType(PublicEventEntryScreen), findsOneWidget);
    expect(find.text('공개 이벤트 입장'), findsOneWidget);
  });

  testWidgets('401 on updateScore navigates to entry screen', (tester) async {
    await tester.pumpWidget(MaterialApp(
      home: PublicEventScreen(publicHash: 'abc', service: StubUpdate401Service()),
    ));

    await tester.pumpAndSettle();
    expect(find.byKey(const Key('participant_tile_p1')), findsOneWidget);

    await tester.tap(find.byKey(const Key('participant_tile_p1')));
    await tester.pumpAndSettle();

    await tester.enterText(find.byKey(const Key('score_input')), '150');
    await tester.tap(find.byKey(const Key('score_save_button')));
    await tester.pumpAndSettle();

    expect(find.byType(PublicEventEntryScreen), findsOneWidget);
    expect(find.text('공개 이벤트 입장'), findsOneWidget);
  });
}
