package app.closer.ui.answers

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.domain.model.LocalAnswer
import app.closer.domain.repository.LocalAnswerRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class AnswerHistoryUiState(
    val answers: List<LocalAnswer> = emptyList()
)

@HiltViewModel
class AnswerHistoryViewModel @Inject constructor(
    private val localAnswerRepository: LocalAnswerRepository
) : ViewModel() {

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

    init {
        viewModelScope.launch {
            localAnswerRepository.observeAnswers().collect { answers ->
                _uiState.value = AnswerHistoryUiState(
                    answers = answers.sortedByDescending { it.updatedAt }
                )
            }
        }
    }

    fun deleteAnswer(questionId: String) {
        viewModelScope.launch {
            localAnswerRepository.deleteAnswer(questionId)
        }
    }
}
