package com.diegocayo.organizame.presentation.features

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.diegocayo.organizame.domain.usecase.IsLoggedInUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject

@HiltViewModel
class MainViewModel @Inject constructor(
    private val isLoggedInUseCase: IsLoggedInUseCase
) : ViewModel() {

    var isLoading by mutableStateOf(true)
        private set

    var isLoggedIn by mutableStateOf(false)
        private set

    var error by mutableStateOf<String?>(null)
        private set

    init {
        checkLoginStatus()
    }

    private fun checkLoginStatus() {
        isLoggedInUseCase.prepare(Unit)
            .onEach { loggedIn ->
                isLoggedIn = loggedIn
                isLoading = false
            }
            .catch { exception ->
                error = exception.message
                isLoading = false
            }
            .launchIn(viewModelScope)
    }
}