package de.haushalt.app.ui.schema

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import de.haushalt.app.data.ApiClient
import de.haushalt.app.data.TaskSchema
import kotlinx.coroutines.launch

class SchemaAllViewModel : ViewModel() {
    var schemas by mutableStateOf<List<TaskSchema>>(emptyList())
        private set
    var isLoading by mutableStateOf(false)
        private set
    var error by mutableStateOf<String?>(null)
        private set

    init {
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            isLoading = true
            error = null
            try {
                schemas = ApiClient.schemaApi.list()
            } catch (e: Exception) {
                error = e.message
            } finally {
                isLoading = false
            }
        }
    }

    fun delete(id: Int) {
        viewModelScope.launch {
            try {
                ApiClient.schemaApi.delete(id)
                schemas = schemas.filter { it.id != id }
            } catch (e: Exception) {
                error = e.message
            }
        }
    }
}
