import 'dart:async'; import 'package:flutter_test/flutter_test.dart'; import 'package:prediqo_mobile/data/models/balance_model.dart'; import 'package:prediqo_mobile/data/models/referral_models.dart'; import 'package:prediqo_mobile/data/models/test_wallet_models.dart'; import 'package:prediqo_mobile/data/models/transaction_model.dart'; import 'package:prediqo_mobile/data/models/wallet_type_model.dart'; import 'package:prediqo_mobile/data/repositories/wallet_repository_impl.dart'; import 'package:prediqo_mobile/domain/repositories/health_repository.dart'; import 'package:prediqo_mobile/domain/repositories/referral_repository.dart'; import 'package:prediqo_mobile/features/wallet/bloc/wallet_bloc.dart'; const _usdt = WalletTypeModel( id: 1, code: 'USDT_TRC20', name: 'USDT', network: 'TRON', decimals: 6, ); BalanceModel _balance({String available = '10690000'}) => BalanceModel( walletType: _usdt, available: available, locked: '0', bonusAvailable: '0', testAvailable: '5000000', ); TransactionModel _tx(String id) => TransactionModel( id: id, walletTypeId: 1, type: 'deposit', amount: '1000000', fee: '0', status: 'completed', createdAt: '2026-09-24T10:00:00.000Z', ); class _FakeWalletRepo implements WalletRepository { int typesCalls = 0; int balancesCalls = 0; int txCalls = 0; final List txCategories = []; final List txOffsets = []; Completer? typesHold; Completer? extrasHold; List page = [_tx('d1')]; String? failCategory; @override Future> getWalletTypes() async { typesCalls++; if (typesHold != null) await typesHold!.future; return const [_usdt]; } @override Future> getBalances() async { balancesCalls++; return [_balance()]; } @override Future> getTransactions({ int limit = 50, int offset = 0, String? category, }) async { txCalls++; txCategories.add(category); txOffsets.add(offset); if (failCategory != null && category == failCategory) { throw Exception('tx down'); } return page; } @override Future getTestWalletStatus() async { if (extrasHold != null) await extrasHold!.future; return const TestWalletStatusModel( enabled: true, balanceRaw: '5000000', walletTypeId: 1, decimals: 6, creditAmountRaw: '10000000', maxRequests: 3, requestsUsed: 0, canRequest: true, ); } @override Future requestTestCredits() async { throw UnimplementedError(); } @override Future getDepositAddress(String walletType) async { throw UnimplementedError(); } @override Future withdraw( String walletType, String toAddress, String amount, { String? totpCode, }) async { return const WithdrawResult(transactionId: 'w1', status: 'pending'); } @override Future transfer( String toEmail, String walletType, String amount, { String? totpCode, }) async { throw UnimplementedError(); } } class _FakeHealth implements HealthRepository { Completer? hold; @override Future getHealth() async { if (hold != null) await hold!.future; return const HealthStatus( network: 'mainnet', withdrawalsEnabled: true, env: 'test', withdrawalNetworkFeeRaw: '1000000', ); } } class _FakeReferral implements ReferralRepository { @override ReferralDashboardModel? peekLastDashboard({int maxDepth = 1}) => null; @override ReferralDashboardModel? peekFreshDashboard({int maxDepth = 1}) => null; @override ReferralCommissionsPage? peekLastCommissions() => null; @override void invalidateDashboard({int? maxDepth}) {} @override void invalidateCommissions() {} @override Future getDashboard({ int maxDepth = 10, bool force = false, }) async { throw UnimplementedError(); } @override Future getCommissions({ int limit = 25, int offset = 0, bool force = false, }) { throw UnimplementedError(); } @override Future<({List balances, bool bonusWithdrawable})> getBonusBalances() async => (balances: [], bonusWithdrawable: true); @override Future transferBonusToMain({ required int walletTypeId, required String amountRaw, }) async {} } Future _settle() => Future.delayed(const Duration(milliseconds: 20)); void main() { late _FakeWalletRepo wallet; late _FakeHealth health; late WalletBloc bloc; setUp(() { wallet = _FakeWalletRepo(); health = _FakeHealth(); bloc = WalletBloc(wallet, health, _FakeReferral()); }); tearDown(() async { await bloc.close(); }); test('emits balances before slower wallet-types (soldes d’abord)', () async { wallet.typesHold = Completer(); bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere((s) => s.balances.isNotEmpty); expect(bloc.state.balances.single.available, '10690000'); expect(bloc.state.isLoading, isFalse); expect(bloc.state.walletTypes, isEmpty); wallet.typesHold!.complete(); await bloc.stream.firstWhere((s) => s.walletTypes.isNotEmpty); expect(bloc.state.walletTypes, isNotEmpty); }); test('full load prefetches Deposits then Withdrawals and Transfers, not Predictions', () async { bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere( (s) => s.deposits.loaded && s.withdrawals.loaded && s.transfers.loaded, ); await _settle(); expect(wallet.balancesCalls, 1); expect(wallet.txCategories, containsAll(['deposits', 'withdrawals', 'transfers'])); expect(wallet.txCategories, isNot(contains('predictions'))); expect(bloc.state.predictions.loaded, isFalse); }); test('ifStale skips a second load within the short cache window', () async { bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere((s) => s.healthLoaded); await _settle(); expect(wallet.balancesCalls, 1); bloc.add(const WalletLoadRequested(ifStale: true)); await _settle(); expect(wallet.balancesCalls, 1); }); test('Predictions stay on-demand and do not reload balances', () async { bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere( (s) => s.deposits.loaded && s.withdrawals.loaded && s.transfers.loaded, ); final balanceCalls = wallet.balancesCalls; final txBeforePredictions = wallet.txCalls; bloc.add(const WalletActivityRequested(category: 'predictions')); await bloc.stream.firstWhere((s) => s.predictions.loaded); expect(wallet.txCategories, contains('predictions')); expect(wallet.txCalls, txBeforePredictions + 1); expect(wallet.balancesCalls, balanceCalls); }); test('Activity cache skips a repeat visit within the short window', () async { bloc.add(const WalletActivityRequested(category: 'deposits')); await bloc.stream.firstWhere((s) => s.deposits.loaded); expect(wallet.txCalls, 1); bloc.add(const WalletActivityRequested(category: 'deposits')); await _settle(); expect(wallet.txCalls, 1); }); test('Activity force refetch ignores the short cache', () async { bloc.add(const WalletActivityRequested(category: 'deposits')); await bloc.stream.firstWhere((s) => s.deposits.loaded); wallet.page = [_tx('forced')]; bloc.add(const WalletActivityRequested(category: 'deposits', force: true)); await bloc.stream.firstWhere((s) => s.deposits.items.length == 1 && s.deposits.items.single.id == 'forced'); expect(wallet.txCalls, 2); }); test('Activity more appends the next page without a full wallet load', () async { wallet.page = List.generate(10, (i) => _tx('p$i')); bloc.add(const WalletActivityRequested(category: 'deposits')); await bloc.stream.firstWhere((s) => s.deposits.loaded); expect(bloc.state.deposits.hasMore, isTrue); wallet.page = [_tx('extra')]; bloc.add(const WalletActivityMoreRequested(category: 'deposits')); await bloc.stream.firstWhere((s) => s.deposits.items.length == 11); expect(wallet.txOffsets, [0, 10]); expect(wallet.balancesCalls, 0); expect(bloc.state.deposits.hasMore, isFalse); }); test('WalletBloc can be constructed with the WalletRepository interface', () async { final extra = WalletBloc(wallet, health, _FakeReferral()); expect(extra, isA()); await extra.close(); }); test('slow extras do not block the first balances emit', () async { health.hold = Completer(); wallet.extrasHold = Completer(); bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere((s) => s.balances.isNotEmpty); expect(bloc.state.healthLoaded, isFalse); expect(bloc.state.testWalletStatus, isNull); health.hold!.complete(); wallet.extrasHold!.complete(); await bloc.stream.firstWhere((s) => s.healthLoaded); expect(bloc.state.bonusWithdrawable, isTrue); }); test('a withdrawal force-refetches the Withdrawals tab so the action is visible', () async { bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere((s) => s.walletTypes.isNotEmpty && s.withdrawals.loaded); wallet.page = [_tx('new-withdrawal')]; bloc.add(const WalletWithdrawRequested( walletType: 'USDT_TRC20', toAddress: 'Txyz', amount: '1000000', )); await bloc.stream.firstWhere( (s) => s.withdrawals.items.any((t) => t.id == 'new-withdrawal'), ); }); test('force load invalidates Activity TTL and refetches Deposits', () async { bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere((s) => s.deposits.loaded); final txAfterWarm = wallet.txCalls; wallet.page = [_tx('after-mutation')]; bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere( (s) => s.deposits.items.any((t) => t.id == 'after-mutation'), ); expect(wallet.txCalls, greaterThan(txAfterWarm)); }); test('deposits failure surfaces Activity error without clearing balances', () async { wallet.failCategory = 'deposits'; bloc.add(const WalletLoadRequested()); await bloc.stream.firstWhere( (s) => s.balances.isNotEmpty && s.deposits.error != null, ); expect(bloc.state.balances, isNotEmpty); expect(bloc.state.deposits.loading, isFalse); expect(bloc.state.deposits.error, isNotEmpty); wallet.failCategory = null; wallet.page = [_tx('recovered')]; bloc.add(const WalletActivityRequested(category: 'deposits', force: true)); await bloc.stream.firstWhere((s) => s.deposits.loaded && s.deposits.items.any((t) => t.id == 'recovered')); expect(bloc.state.deposits.error, isNull); }); }