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

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.runicgateway.app.data.api.dto.WikiSummaryDto
import com.runicgateway.app.data.repository.WikiRepository
import com.runicgateway.app.ui.UiState
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

/** Wiki index with full-text search (PLAN.md §6.1). */
@HiltViewModel
class WikiViewModel @Inject constructor(
    private val wikiRepository: WikiRepository,
) : ViewModel() {

    private val _query = MutableStateFlow("")
    val query: StateFlow<String> = _query.asStateFlow()

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

    init { load() }

    fun onQueryChange(value: String) {
        _query.value = value
    }

    /** Run the current query (invoked on submit; blank query lists all pages). */
    fun load() {
        _state.value = UiState.Loading
        viewModelScope.launch {
            _state.value = wikiRepository.getPages(query = _query.value).toUiState()
        }
    }
}
