package de.tsschulz.tt_tagebuch.app.viewmodel

import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import de.tsschulz.tt_tagebuch.shared.repository.AuthRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class LoginScreenModel(private val authRepository: AuthRepository) : ScreenModel {
    private val _state = MutableStateFlow<LoginState>(LoginState.Idle)
    val state = _state.asStateFlow()

    fun login(email: String, password: String) {
        screenModelScope.launch {
            _state.value = LoginState.Loading
            try {
                val response = authRepository.login(email, password)
                if (response.success) {
                    _state.value = LoginState.Success
                } else {
                    _state.value = LoginState.Error(response.error ?: "Unknown error")
                }
            } catch (e: Exception) {
                _state.value = LoginState.Error(e.message ?: "Network error")
            }
        }
    }
}

sealed class LoginState {
    object Idle : LoginState()
    object Loading : LoginState()
    object Success : LoginState()
    data class Error(val message: String) : LoginState()
}
