package com.syaroful.agrilinkvocpro.presentation.screen.register

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.syaroful.agrilinkvocpro.core.utils.ResultState
import com.syaroful.agrilinkvocpro.core.utils.extention.mapToUserFriendlyError
import com.syaroful.agrilinkvocpro.data.model.RegisterResponse
import com.syaroful.agrilinkvocpro.data.repository.AuthRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class RegisterViewModel(
    private val authRepository: AuthRepository,
) : ViewModel() {
    private val _signupState = MutableStateFlow<ResultState<RegisterResponse>>(ResultState.Idle)
    val signupState: StateFlow<ResultState<RegisterResponse>> = _signupState

    fun signup(name: String, username: String, email: String, password: String) {
        _signupState.value = ResultState.Loading
        viewModelScope.launch {
            try {
                val response = authRepository.register(username, password, email, name)
                if (response.isSuccessful) {
                    _signupState.value = ResultState.Success(response.body())
                } else {
                    val errorMessage = response.body()?.message ?: "Register Failed"
                    _signupState.value = ResultState.Error(errorMessage)
                }
            } catch (e: Exception) {
                val errorMessage = mapToUserFriendlyError(e)
                _signupState.value = ResultState.Error(errorMessage)
            }
        }
    }

    fun resetRegisterState(){
        _signupState.value = ResultState.Idle

    }
}