import 'dart:async'; import 'package:dio/dio.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:prediqo_mobile/core/config/app_config.dart'; import 'package:prediqo_mobile/features/prediction/presentation/prediction_screen.dart'; import 'package:prediqo_mobile/core/di/injection.dart'; import 'package:prediqo_mobile/core/network/api_client.dart'; import 'package:prediqo_mobile/core/realtime/support_socket_service.dart'; import 'package:prediqo_mobile/data/models/support_models.dart'; import 'package:prediqo_mobile/data/repositories/support_repository.dart'; import 'package:prediqo_mobile/features/support/bloc/support_bloc.dart'; import 'package:prediqo_mobile/features/support/utils/support_ui_gate.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'support/e2e_fixtures.dart'; SupportMessageModel _msg(String id, {String body = 'Hello support'}) => SupportMessageModel( id: id, conversationId: 'c1', senderType: 'user', createdAt: '2026-09-24T10:00:00.000Z', body: body, ); class _FakeSupport extends SupportRepository { _FakeSupport(super.api); Completer? convHold; Completer? messagesHold; Object? failWith; Object? sendFail; var findCalls = 0; var messageCalls = 0; var sendCalls = 0; SupportConversationModel? conversation = const SupportConversationModel(id: 'c1', status: 'open'); List messages = [_msg('m1')]; @override Future findCurrentConversation() async { findCalls++; if (failWith != null) throw failWith!; if (convHold != null) return convHold!.future; return conversation; } @override Future getMessages(String conversationId) async { messageCalls++; if (failWith != null) throw failWith!; if (messagesHold != null) return messagesHold!.future; return SupportMessagesPage(messages: List.of(messages), staffTyping: false); } @override Future sendMessage(String? conversationId, String body) async { sendCalls++; if (sendFail != null) throw sendFail!; return _msg('sent-$sendCalls', body: body); } @override Future sendImage(String? conversationId, String filePath) async { sendCalls++; if (sendFail != null) throw sendFail!; return SupportMessageModel( id: 'img-$sendCalls', conversationId: conversationId ?? 'c1', senderType: 'user', createdAt: '2026-09-24T10:00:00.000Z', attachmentUrl: '/uploads/img-$sendCalls.jpg', attachmentName: 'img-$sendCalls.jpg', attachmentMime: 'image/jpeg', ); } @override Future setTyping(String conversationId, bool active) async {} } Future<({_FakeSupport repo, SupportSocketService socket})> _boot() async { configureE2eTestEnvironment(); if (sl.isRegistered()) await sl.reset(); const config = AppConfig( apiBaseUrl: 'http://localhost', isProduction: false, wsEnabled: false, ); sl.registerSingleton(config); SharedPreferences.setMockInitialValues({}); final api = ApiClient(config: config); sl.registerLazySingleton(() => api); final repo = _FakeSupport(api); final socket = SupportSocketService(config, api, repo); return (repo: repo, socket: socket); } Future _waitUntil( SupportBloc bloc, bool Function(SupportState s) pred, { Duration timeout = const Duration(seconds: 2), }) async { if (pred(bloc.state)) return; await bloc.stream.firstWhere(pred).timeout(timeout); } void main() { tearDown(() async { if (sl.isRegistered()) await sl.reset(); }); test('prediction resume reconnect ignores sheet/IME lifecycle blips', () { expect(predictionIsRealBackgroundLifecycle(AppLifecycleState.inactive), isFalse); expect(predictionIsRealBackgroundLifecycle(AppLifecycleState.hidden), isFalse); expect(predictionIsRealBackgroundLifecycle(AppLifecycleState.resumed), isFalse); expect(predictionIsRealBackgroundLifecycle(AppLifecycleState.paused), isTrue); expect(predictionIsRealBackgroundLifecycle(AppLifecycleState.detached), isTrue); expect(predictionBackgroundDwellAllowsReconnect(null), isFalse); expect( predictionBackgroundDwellAllowsReconnect(const Duration(milliseconds: 400)), isFalse, ); expect( predictionBackgroundDwellAllowsReconnect(const Duration(milliseconds: 1500)), isTrue, ); }); test('first open emits loading then paints messages (no blank error)', () async { final boot = await _boot(); final hold = Completer(); boot.repo.messagesHold = hold; final bloc = SupportBloc(boot.repo, boot.socket); bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.loading && s.messages.isEmpty && s.open); expect(bloc.state.errorMessage, isNull); hold.complete( SupportMessagesPage( messages: [_msg('m1', body: 'Loaded thread')], staffTyping: false, ), ); await _waitUntil(bloc, (s) => !s.loading && s.messages.isNotEmpty); expect(bloc.state.messages.single.body, 'Loaded thread'); expect(bloc.state.retrying, isFalse); bloc.add(const SupportPanelClosed()); await bloc.close(); }); test('load failure keeps retryable error; retry recovers', () async { final boot = await _boot(); boot.repo.failWith = Exception('offline'); final bloc = SupportBloc(boot.repo, boot.socket); bloc.add(const SupportPanelOpened()); await _waitUntil( bloc, (s) => s.errorMessage != null && !s.loading && s.messages.isEmpty, ); expect(bloc.state.retrying, isFalse); boot.repo.failWith = null; boot.repo.messagesHold = Completer(); final before = boot.repo.findCalls; bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.retrying && s.errorMessage != null); expect(boot.repo.findCalls, greaterThan(before)); boot.repo.messagesHold!.complete( SupportMessagesPage(messages: [_msg('ok', body: 'Recovered')], staffTyping: false), ); await _waitUntil(bloc, (s) => s.messages.isNotEmpty && s.errorMessage == null); expect(bloc.state.messages.single.body, 'Recovered'); expect(bloc.state.retrying, isFalse); bloc.add(const SupportPanelClosed()); await bloc.close(); }); test('reopen soft-refreshes without clearing painted messages', () async { final boot = await _boot(); final bloc = SupportBloc(boot.repo, boot.socket); bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.messages.isNotEmpty); expect(bloc.state.messages.single.body, 'Hello support'); bloc.add(const SupportPanelClosed()); await _waitUntil(bloc, (s) => !s.open); boot.repo.messagesHold = Completer(); bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.open); expect(bloc.state.loading, isFalse); expect(bloc.state.messages.single.body, 'Hello support'); boot.repo.messagesHold!.complete( SupportMessagesPage( messages: [_msg('m2', body: 'Fresh message')], staffTyping: false, ), ); await _waitUntil(bloc, (s) => s.messages.single.body == 'Fresh message'); bloc.add(const SupportPanelClosed()); await bloc.close(); }); test('soft-fail refresh keeps thread when getMessages throws', () async { final boot = await _boot(); final bloc = SupportBloc(boot.repo, boot.socket); bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.messages.isNotEmpty); boot.repo.failWith = Exception('offline'); bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.open && !s.loading); // Allow the in-flight soft refresh to settle. await Future.delayed(const Duration(milliseconds: 30)); expect(bloc.state.messages, isNotEmpty); expect(bloc.state.errorMessage, isNull); bloc.add(const SupportPanelClosed()); await bloc.close(); }); test('queues text offline then flushes when send recovers', () async { final boot = await _boot(); final bloc = SupportBloc(boot.repo, boot.socket); bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.messages.isNotEmpty); boot.repo.sendFail = DioException( requestOptions: RequestOptions(path: '/support'), type: DioExceptionType.connectionError, ); bloc.add(const SupportSendRequested('queued hello')); await _waitUntil( bloc, (s) => s.messages.any((m) => m.isPending && m.body == 'queued hello'), ); expect(bloc.state.errorMessage, isNull); boot.repo.sendFail = null; bloc.add(const SupportOutboxFlushRequested()); await _waitUntil( bloc, (s) => s.messages.any((m) => m.body == 'queued hello' && !m.isPending) && s.messages.every((m) => !m.isPending), ); bloc.add(const SupportPanelClosed()); await bloc.close(); }); test('queues image offline then flushes when send recovers', () async { final boot = await _boot(); final bloc = SupportBloc(boot.repo, boot.socket); bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.messages.isNotEmpty); boot.repo.sendFail = DioException( requestOptions: RequestOptions(path: '/support'), type: DioExceptionType.connectionError, ); bloc.add(const SupportImageSendRequested('/tmp/photo.jpg')); await _waitUntil( bloc, (s) => s.messages.any((m) => m.isPending && m.attachmentUrl == '/tmp/photo.jpg'), ); expect(bloc.state.errorMessage, isNull); boot.repo.sendFail = null; bloc.add(const SupportOutboxFlushRequested()); await _waitUntil( bloc, (s) => s.messages.any( (m) => !m.isPending && (m.attachmentUrl ?? '').startsWith('/uploads/'), ) && s.messages.every((m) => !m.isPending), ); bloc.add(const SupportPanelClosed()); await bloc.close(); }); test('markPanelOpening suppresses game reconnect before open settles', () async { final boot = await _boot(); final bloc = SupportBloc(boot.repo, boot.socket); SupportUiGate.holdsGameRealtime = false; SupportUiGate.predictionScreenActive = false; expect(bloc.suppressesGameReconnect, isFalse); bloc.markPanelOpening(); expect(bloc.suppressesGameReconnect, isTrue); expect(SupportUiGate.holdsGameRealtime, isTrue); bloc.add(const SupportPanelOpened()); await _waitUntil(bloc, (s) => s.open); expect(bloc.suppressesGameReconnect, isTrue); bloc.add(const SupportPanelClosed()); await _waitUntil(bloc, (s) => !s.open); expect(bloc.suppressesGameReconnect, isFalse); expect(SupportUiGate.holdsGameRealtime, isFalse); await bloc.close(); }); test('defers Support WS while Predict screen is active', () { SupportUiGate.holdsGameRealtime = true; SupportUiGate.predictionScreenActive = true; expect(SupportUiGate.shouldDeferSupportSocket, isTrue); SupportUiGate.predictionScreenActive = false; expect(SupportUiGate.shouldDeferSupportSocket, isFalse); SupportUiGate.holdsGameRealtime = false; }); }