package com.narutohuo.xindazhou.auth.ui.viewmodel

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

/**
 * 登录ViewModel
 */
class LoginViewModel(
    application: Application,
    private val authRepository: AuthRepository
) : BaseViewModel(application) {
    
    companion object {
        private const val MIN_PASSWORD_LENGTH = 6
        private const val MAX_PASSWORD_LENGTH = 16
        
        // UI 提示信息
        private const val MSG_LOGIN_SUCCESS = "登录成功"
        private const val MSG_LOGIN_FAILED = "登录失败"
    }
    
    private val _loginState = MutableStateFlow<LoginState>(LoginState.Idle)
    val loginState: StateFlow<LoginState> = _loginState
    
    /**
     * 登录
     * 
     * @param mobile 手机号
     * @param password 密码
     */
    fun login(mobile: String, password: String) {
        // 输入验证
        if (mobile.isBlank()) {
            _loginState.value = LoginState.Error("手机号不能为空")
            return
        }
        
        if (password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH) {
            _loginState.value = LoginState.Error("密码长度应为${MIN_PASSWORD_LENGTH}-${MAX_PASSWORD_LENGTH}位")
            return
        }
        
        // 使用 BaseViewModel 提供的 executeRequest 方法（自动处理 Loading/Success/Error）
        executeRequest(
            stateFlow = _loginState,
            onLoading = { LoginState.Loading },
            onSuccess = { LoginState.Success(MSG_LOGIN_SUCCESS) },
            onError = { msg -> LoginState.Error(msg) },
            errorMessage = MSG_LOGIN_FAILED
        ) {
            authRepository.login(mobile, password)
        }
    }
    
    /**
     * 重置登录状态
     */
    fun resetState() {
        _loginState.value = LoginState.Idle
    }
}

