package com.seven.ikar.kotlin.feature.bots

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.model.BotSummaryDto
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class BotsUiState(
    val bots: List<BotSummaryDto> = emptyList(),
    val isLoading: Boolean = false,
    val errorMessage: String? = null
)

class BotsViewModel(private val container: AppContainer) : ViewModel() {
    private val _uiState = MutableStateFlow(BotsUiState())
    val uiState: StateFlow<BotsUiState> = _uiState.asStateFlow()

    init {
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null)
            runCatching {
                container.executeAuthorized { session ->
                    container.apiClient.getMyBots(session.accessToken)
                }
            }.onSuccess { bots ->
                _uiState.value = _uiState.value.copy(bots = bots, isLoading = false, errorMessage = null)
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(isLoading = false, errorMessage = error.message)
            }
        }
    }
}
