package com.seven.ikar.kotlin.feature.devices

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

data class DevicesUiState(
    val devices: List<PushDeviceDto> = emptyList(),
    val currentInstallationId: String = "",
    val isLoading: Boolean = false,
    val errorMessage: String? = null
)

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

    init {
        refresh()
    }

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