import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../core/api/api_exception.dart'; import '../data/wallet_repository.dart'; /// خطوتا السحب (docs/38 §6): `request` يرسل رمزاً **بلا خصم**، و`confirm` /// هو ما يخصم ويحجز. شاشة سيرو كانت خطوة واحدة — لا تُقلَّد (docs/39 §4). enum PayoutStep { amount, code, done } enum PayoutFailure { none, insufficient, rejected, network } class PayoutState { const PayoutState({ this.step = PayoutStep.amount, this.busy = false, this.payoutId, this.devCode, this.failure = PayoutFailure.none, }); final PayoutStep step; final bool busy; final String? payoutId; /// يعود من الخادم في وضع التطوير وحده — يملأ الحقل لتسريع الاختبار. final String? devCode; final PayoutFailure failure; PayoutState copyWith({ PayoutStep? step, bool? busy, String? payoutId, String? devCode, PayoutFailure? failure, }) { return PayoutState( step: step ?? this.step, busy: busy ?? this.busy, payoutId: payoutId ?? this.payoutId, devCode: devCode ?? this.devCode, failure: failure ?? this.failure, ); } } class PayoutCubit extends Cubit { PayoutCubit(this._repo) : super(const PayoutState()); final WalletRepository _repo; Future request({required num amount, required String channel}) async { if (amount <= 0) return; emit(state.copyWith(busy: true, failure: PayoutFailure.none)); try { final res = await _repo.requestPayout(amount: amount, channel: channel); emit(state.copyWith( busy: false, step: PayoutStep.code, payoutId: res.payoutId, devCode: res.devCode, )); } on ApiException catch (e) { emit(state.copyWith( busy: false, failure: e.statusCode == 400 ? PayoutFailure.insufficient : PayoutFailure.network, )); } } Future confirm(String code) async { final id = state.payoutId; if (id == null || code.isEmpty) return; emit(state.copyWith(busy: true, failure: PayoutFailure.none)); try { await _repo.confirmPayout(id, code); emit(state.copyWith(busy: false, step: PayoutStep.done)); } on ApiException { // الرمز الخاطئ لا يُرجع المستخدم لخطوة المبلغ: يبقى على الرمز ويعيد // المحاولة — الطلب قائم على الخادم أصلاً. emit(state.copyWith(busy: false, failure: PayoutFailure.rejected)); } } void reset() => emit(const PayoutState()); }