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 RegisterState {
    object Idle : RegisterState()
    object Loading : RegisterState()
    data class Success(val message: String) : RegisterState()
    data class Error(val message: String) : RegisterState()
}

/**
 * 注册ViewModel
 */
class RegisterViewModel(
    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 _registerState = MutableStateFlow<RegisterState>(RegisterState.Idle)
    val registerState: StateFlow<RegisterState> = _registerState
    
    /**
     * 注册
     * 
     * @param mobile 手机号
     * @param password 密码
     */
    fun register(mobile: String, password: String) {
        viewModelScope.launch {
            _registerState.value = RegisterState.Loading
            
            // 输入验证
            if (mobile.isBlank()) {
                _registerState.value = RegisterState.Error("手机号不能为空")
                return@launch
            }
            
            if (password.length < MIN_PASSWORD_LENGTH || password.length > MAX_PASSWORD_LENGTH) {
                _registerState.value = RegisterState.Error("密码长度应为${MIN_PASSWORD_LENGTH}-${MAX_PASSWORD_LENGTH}位")
                return@launch
            }
            
            authRepository.register(mobile, password)
                .onSuccess {
                    _registerState.value = RegisterState.Success(UiConstants.MSG_REGISTER_SUCCESS)
                }
                .onFailure { e ->
                    _registerState.value = RegisterState.Error(e.message ?: UiConstants.MSG_REGISTER_FAILED)
                }
        }
    }
}
