/*
 * 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.ErrorKind
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

/** Loads a single post for the detail screen (PLAN.md §6.1). */
@HiltViewModel
class PostViewModel @Inject constructor(
    private val contentRepository: ContentRepository,
    savedStateHandle: SavedStateHandle,
) : ViewModel() {

    private val categorySlug: String? = savedStateHandle[Routes.Args.CATEGORY]
    private val idOrSlug: String = savedStateHandle[Routes.Args.ID_OR_SLUG] ?: ""

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

    init { load() }

    fun load() {
        val category = PostCategory.fromUrlSlug(categorySlug)
        if (category == null) {
            _state.value = UiState.Error(ErrorKind.NOT_FOUND)
            return
        }
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = contentRepository.getPost(category, idOrSlug).toUiState()
        }
    }
}
