package com.optix.android.ui.screens.settings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.optix.android.domain.model.AiProviderConfig
import com.optix.android.domain.model.AppSettings
import com.optix.android.domain.model.NetworkSettings
import com.optix.android.domain.repository.SettingsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SettingsViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository,
) : ViewModel() {

    val aiConfig: StateFlow<AiProviderConfig> = settingsRepository.getAiConfig()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AiProviderConfig())

    val appSettings: StateFlow<AppSettings> = settingsRepository.getAppSettings()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AppSettings())

    val networkSettings: StateFlow<NetworkSettings> = settingsRepository.getNetworkSettings()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NetworkSettings())

    fun saveAiConfig(config: AiProviderConfig) {
        viewModelScope.launch { settingsRepository.saveAiConfig(config) }
    }

    fun saveAppSettings(settings: AppSettings) {
        viewModelScope.launch { settingsRepository.saveAppSettings(settings) }
    }

    fun saveNetworkSettings(settings: NetworkSettings) {
        viewModelScope.launch { settingsRepository.saveNetworkSettings(settings) }
    }
}
