package ru.fincode.tsudesk.feature.splash.presentation.screen

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import ru.fincode.tsudesk.core.common.model.DataResult
import ru.fincode.tsudesk.core.config.domain.usecase.GetConfigUseCase
import ru.fincode.tsudesk.feature.splash.presentation.model.SplashEffect
import ru.fincode.tsudesk.feature.splash.presentation.model.SplashUiState
import javax.inject.Inject

@HiltViewModel
class SplashViewModel @Inject constructor(
    private val getConfigUseCase: GetConfigUseCase
) : ViewModel() {
    private val _state = MutableStateFlow(SplashUiState(isLoading = true))
    private val _effects = MutableSharedFlow<SplashEffect>(extraBufferCapacity = 1)
    val state: StateFlow<SplashUiState> = _state.asStateFlow()
    val effects: SharedFlow<SplashEffect> = _effects.asSharedFlow()

    init {
        viewModelScope.launch {
            val errorMessage = when (val result = getConfigUseCase()) {
                is DataResult.Data -> null
                is DataResult.Error -> result.error.toString()
                is DataResult.Loading -> null
            }
            _state.update {
                it.copy(
                    isLoading = false,
                    errorMessage = errorMessage
                )
            }
            _effects.tryEmit(SplashEffect.OpenMain)
        }
    }
}
