package de.krisenvorrat.app.ui.warnings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.krisenvorrat.app.domain.repository.ItemRepository
import de.krisenvorrat.app.domain.usecase.GetExpiryWarningsUseCase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
internal class WarningsViewModel @Inject constructor(
    private val itemRepository: ItemRepository,
    private val getExpiryWarnings: GetExpiryWarningsUseCase
) : ViewModel() {

    private val _uiState = MutableStateFlow(WarningsUiState())
    val uiState: StateFlow<WarningsUiState> = _uiState.asStateFlow()

    init {
        viewModelScope.launch {
            itemRepository.getAll().collect { items ->
                _uiState.update {
                    WarningsUiState(
                        expiryWarnings = getExpiryWarnings(items),
                        isLoading = false
                    )
                }
            }
        }
    }
}
