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/services/public_event_service.dart';

class StubSuccessService extends PublicEventService {
  @override
  Future<Map<String, dynamic>> enter(String publicHash, {String? password}) async {
    // 즉시 성공(토큰 포함)
    return {'token': 'TKN', 'event': {'id': 'E1'}};
  }
}

class StubNeedPasswordThenSuccessService extends PublicEventService {
  bool first = true;
  @override
  Future<Map<String, dynamic>> enter(String publicHash, {String? password}) async {
    if (first) {
      first = false;
      throw Exception('401 need password');
    }
    if (password == 'pw') {
      return {'token': 'TKN2', 'event': {'id': 'E2'}};
    }
    throw Exception('wrong password');
  }
}

void main() {
  testWidgets('auto enter success navigates to PublicEventScreen', (tester) async {
    await tester.pumpWidget(MaterialApp(
      home: PublicEventEntryScreen(publicHash: 'auto', service: StubSuccessService()),
    ));

    await tester.pump();
    await tester.pump(const Duration(milliseconds: 50));
    await tester.pumpAndSettle();

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

  testWidgets('needs password then success on submit', (tester) async {
    await tester.pumpWidget(MaterialApp(
      home: PublicEventEntryScreen(publicHash: 'needpw', service: StubNeedPasswordThenSuccessService()),
    ));

    // 초기 자동 진입 실패 → 비밀번호 UI 노출
    await tester.pump();
    await tester.pumpAndSettle();
    expect(find.byKey(const Key('public_password_field')), findsOneWidget);

    // 비밀번호 입력 후 제출
    await tester.enterText(find.byKey(const Key('public_password_field')), 'pw');
    await tester.tap(find.byKey(const Key('public_enter_submit')));
    await tester.pumpAndSettle();

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