package org.zaine.management.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.zaine.management.data.BackendRepository
import org.zaine.management.data.NetworkResult
import org.zaine.management.data.TodayBundle
import javax.inject.Inject

data class TodayUiState(
    val loading: Boolean = false,
    val data: TodayBundle? = null,
    val error: String? = null
)

@HiltViewModel
class TodayViewModel @Inject constructor(
    private val repository: BackendRepository
) : ViewModel() {
    private val _state = MutableStateFlow(TodayUiState(loading = true))
    val state: StateFlow<TodayUiState> = _state.asStateFlow()

    init {
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            _state.value = _state.value.copy(loading = true, error = null)
            when (val result = repository.today()) {
                is NetworkResult.Success -> _state.value = TodayUiState(data = result.data)
                is NetworkResult.Error -> _state.value = TodayUiState(error = result.message)
                NetworkResult.Loading -> Unit
            }
        }
    }
}
