package com.bilimway.payme import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch /** * Modern Jetpack Architecture ViewModel that mediates inputs, handles loading states, * tracks sequential stages, formats errors, and securely executes Payme card transactions. */ class PaymeViewModel(private val repository: PaymeRepository) : ViewModel() { // Immutable Flow state for UI observer private val _uiState = MutableStateFlow(PaymeUiState.Idle) val uiState: StateFlow = _uiState.asStateFlow() // Observable states mutable directly in UI forms var cardNumber by mutableStateOf("") var cardExpiry by mutableStateOf("") var amountUzs by mutableStateOf("") var otpCode by mutableStateOf("") // Persistent balances in app sandbox for demo simulation private val _userBalance = MutableStateFlow(350000L) // Default mock balance of 350,000 UZS val userBalance: StateFlow = _userBalance.asStateFlow() // Internal state variables private var currentCardToken: String? = null var processedAmount: Long = 0L private set /** * UI Action to submit Card Number and Amount UZS. * Transitions from Idle/Form to registering card and waiting for SMS payload. */ fun initiatePayment() { val cleanCard = cardNumber.replace(" ", "") val cleanExpiry = cardExpiry.replace("/", "") val amount = amountUzs.toLongOrNull() ?: 0L // Validation Rules if (cleanCard.length != 16) { _uiState.value = PaymeUiState.Error("Karta raqami 16 xonali bo'lishi shart!") return } if (cleanExpiry.length != 4) { _uiState.value = PaymeUiState.Error("Amal qilish muddati noto'g'ri kiritilgan! (AA/YY)") return } if (amount < 5000) { _uiState.value = PaymeUiState.Error("Minimal to'ldirish miqdori 5 000 UZS.") return } processedAmount = amount _uiState.value = PaymeUiState.Loading("Karta ro'yxatdan o'tkazilmoqda...") viewModelScope.launch { repository.registerCard(cleanCard, cleanExpiry) .onSuccess { token -> currentCardToken = token sendOtpCode(token) } .onFailure { error -> _uiState.value = PaymeUiState.Error(error.localizedMessage ?: "Karta tanib olinmadi.") } } } /** * Sends verification code to the phone linked with the registered card token. */ private fun sendOtpCode(token: String) { _uiState.value = PaymeUiState.Loading("Elektron tasdiq kodi SMS orqali yuborilmoqda...") viewModelScope.launch { repository.getVerifyCode(token) .onSuccess { success -> _uiState.value = PaymeUiState.OtpVerification(otpSent = success) } .onFailure { error -> _uiState.value = PaymeUiState.Error(error.localizedMessage ?: "SMS jo'natish xatosi.") } } } /** * UI Action to submit the OTP code. * Performs card verification, processes receipt, then adds UZS to the live user state. */ fun verifyAndCompletePayment() { val code = otpCode.trim() val token = currentCardToken if (code.length != 6) { _uiState.value = PaymeUiState.Error("6 xonali tasdiqlash kodini to'liq kiriting.") return } if (token == null) { _uiState.value = PaymeUiState.Error("To'lov tranzaktsiyasi uzilib qoldi. Qayta urinib ko'ring.") return } _uiState.value = PaymeUiState.Loading("Karta tasdiqlanmoqda va to'lov tushirilmoqda...") viewModelScope.launch { // Verify card with input OTP code repository.verifyCard(token, code) .onSuccess { // Purchase and deposit the amount inside system repository.createAndPayReceipt(token, processedAmount) .onSuccess { _userBalance.value += processedAmount _uiState.value = PaymeUiState.Success(processedAmount) // Reset inputs cardNumber = "" cardExpiry = "" amountUzs = "" otpCode = "" } .onFailure { payErr -> _uiState.value = PaymeUiState.Error(payErr.localizedMessage ?: "To'lovni undirishda xatolik yuz berdi.") } } .onFailure { verifyErr -> _uiState.value = PaymeUiState.Error(verifyErr.localizedMessage ?: "Noto'g'ri tasdiqlash kodi kiritildi!") } } } /** * Back navigation or error resolution helper to reset payment status. */ fun resetStates() { _uiState.value = PaymeUiState.Idle otpCode = "" } } // === UI STATE MODEL REPRESENTATION === sealed interface PaymeUiState { object Idle : PaymeUiState data class Loading(val message: String) : PaymeUiState data class OtpVerification(val otpSent: Boolean) : PaymeUiState data class Success(val refilledAmount: Long) : PaymeUiState data class Error(val errorMessage: String) : PaymeUiState }