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

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.runicgateway.app.data.api.dto.WikiPageDto
import com.runicgateway.app.data.repository.WikiRepository
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 wiki page for the detail screen (PLAN.md §6.1). */
@HiltViewModel
class WikiPageViewModel @Inject constructor(
    private val wikiRepository: WikiRepository,
    savedStateHandle: SavedStateHandle,
) : ViewModel() {

    private val slug: String = savedStateHandle[Routes.Args.SLUG] ?: ""

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

    init { load() }

    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = wikiRepository.getPage(slug).toUiState()
        }
    }
}
