/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.ui.news

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.runicgateway.app.data.api.dto.PostDto
import com.runicgateway.app.data.repository.ContentRepository
import com.runicgateway.app.data.repository.ContentRepository.PostCategory
import com.runicgateway.app.ui.UiState
import com.runicgateway.app.ui.navigation.Routes
import com.runicgateway.app.ui.toUiState
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 javax.inject.Inject

/** News hub: a category selector over the four post feeds (PLAN.md §6.1). */
@HiltViewModel
class NewsViewModel @Inject constructor(
    private val contentRepository: ContentRepository,
    savedStateHandle: SavedStateHandle,
) : ViewModel() {

    // Which tab to open on. Absent — every route into this screen except an
    // admin's nav override or added link (THEMING_AND_NAV.md §6.2) — is the
    // default feed, and so is a slug the app doesn't know.
    private val _category = MutableStateFlow(
        PostCategory.fromUrlSlug(savedStateHandle[Routes.Args.CATEGORY]) ?: PostCategory.NEWS,
    )
    val category: StateFlow<PostCategory> = _category.asStateFlow()

    private val _state = MutableStateFlow<UiState<List<PostDto>>>(UiState.Loading)
    val state: StateFlow<UiState<List<PostDto>>> = _state.asStateFlow()

    init { load() }

    fun selectCategory(category: PostCategory) {
        if (category == _category.value) return
        _category.value = category
        load()
    }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = contentRepository.getPosts(_category.value).toUiState()
        }
    }
}
