package id.iiyh.inatrading.feature.home.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import id.iiyh.inatrading.feature.news.data.model.NewsArticle
import id.iiyh.inatrading.feature.news.domain.NewsRepository
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

data class HomeUiState(
    val latestNews: List<NewsArticle> = emptyList(),
    val isLoadingNews: Boolean = false,
    val newsError: String? = null,
)

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val newsRepository: NewsRepository,
) : ViewModel() {

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

    init {
        loadLatestNews()
    }

    fun loadLatestNews() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoadingNews = true, newsError = null) }
            newsRepository.getArticles()
                .onSuccess { articles ->
                    _uiState.update {
                        it.copy(
                            isLoadingNews = false,
                            latestNews = articles.take(3),
                        )
                    }
                }
                .onFailure { e ->
                    _uiState.update { it.copy(isLoadingNews = false, newsError = e.message) }
                }
        }
    }
}
