package com.narutohuo.xindazhou.user.ui.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.narutohuo.xindazhou.common.auth.repository.AuthRepository
import com.narutohuo.xindazhou.user.ui.constant.UiConstants
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

/**
 * 登录状态
 */
sealed class LoginState {
    object Idle : LoginState()
    object Loading : LoginState()
    data class Success(val message: String) : LoginState()
    data class Error(val message: String) : LoginState()
}

/**
 * 登录ViewModel
 */
class LoginViewModel(
    application: Application,
    private val authRepository: AuthRepository
) : AndroidViewModel(application) {
    
    companion object {
        private const val MIN_PASSWORD_LENGTH = 6
        private const val MAX_PASSWORD_LENGTH = 16
    }
    
    private val _loginState = MutableStateFlow<LoginState>(LoginState.Idle)
    val loginState: StateFlow<LoginState> = _loginState
    
    /**
     * 登录
     * 
     * @param mobile 手机号
     * @param password 密码
     */
    fun login(mobile: String, password: String) {
        viewModelScope.launch {
            _loginState.value = LoginState.Loading
            
            // 输入验证
            if (mobile.isBlank()) {
                _loginState.value = LoginState.Error("手机号不能为空")
                return@launch
            }
            
            if (password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH) {
                _loginState.value = LoginState.Error("密码长度应为${MIN_PASSWORD_LENGTH}-${MAX_PASSWORD_LENGTH}位")
                return@launch
            }
            
            authRepository.login(mobile, password)
                .onSuccess {
                    _loginState.value = LoginState.Success(UiConstants.MSG_LOGIN_SUCCESS)
                }
                .onFailure { e ->
                    _loginState.value = LoginState.Error(e.message ?: UiConstants.MSG_LOGIN_FAILED)
                }
        }
    }
}
