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 RegisterViewModel(
    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_REGISTER_SUCCESS = "注册成功"
        private const val MSG_REGISTER_FAILED = "注册失败"
    }
    
    private val _registerState = MutableStateFlow<RegisterState>(RegisterState.Idle)
    val registerState: StateFlow<RegisterState> = _registerState
    
    /**
     * 注册
     * 
     * @param mobile 手机号
     * @param password 密码
     */
    fun register(mobile: String, password: String) {
        // 输入验证
        if (mobile.isBlank()) {
            _registerState.value = RegisterState.Error("手机号不能为空")
            return
        }
        
        if (password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH) {
            _registerState.value = RegisterState.Error("密码长度应为${MIN_PASSWORD_LENGTH}-${MAX_PASSWORD_LENGTH}位")
            return
        }
        
        // 使用 BaseViewModel 提供的 executeRequest 方法（自动处理 Loading/Success/Error）
        executeRequest(
            stateFlow = _registerState,
            onLoading = { RegisterState.Loading },
            onSuccess = { RegisterState.Success(MSG_REGISTER_SUCCESS) },
            onError = { msg -> RegisterState.Error(msg) },
            errorMessage = MSG_REGISTER_FAILED
        ) {
            authRepository.register(mobile, password)
        }
    }
    
    /**
     * 重置注册状态
     */
    fun resetState() {
        _registerState.value = RegisterState.Idle
    }
}

