package ru.myitschool.work.ui.login

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Response
import ru.myitschool.work.api.login.ApiServiceLogin
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val apiService: ApiServiceLogin
) : ViewModel() {

    private val _state = MutableStateFlow<LoginState>(LoginState.Initial)
    val state = _state.asStateFlow()

    fun authenticate() {
        viewModelScope.launch {
            _state.value = LoginState.Loading

            apiService.authenticate().enqueue(object : retrofit2.Callback<Void> {
                override fun onResponse(call: Call<Void>, response: Response<Void>) {
                    Log.d("Authentication", "Response code: ${response.code()}")

                    when (response.code()) {
                        200 -> {
                            _state.value = LoginState.Success
                        }
                        400 -> {
                            _state.value = LoginState.InvalidCredentials
                        }
                        401 -> {
                            _state.value = LoginState.Error
                        }
                        else -> {
                            _state.value = LoginState.Error
                        }
                    }
                }

                override fun onFailure(call: Call<Void>, t: Throwable) {
                    _state.value = LoginState.Error
                }
            })
        }
    }

    sealed class LoginState {
        data object Initial : LoginState()
        data object Loading : LoginState()
        data object Success : LoginState()
        data object InvalidCredentials : LoginState()
        data object Error : LoginState()
    }
}