package de.trainingstagebuch.app.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.trainingstagebuch.app.network.NetworkModule
import de.trainingstagebuch.app.services.AppServices
import de.trainingstagebuch.app.utils.SessionGuardUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class AppViewModel(application: Application) : AndroidViewModel(application) {

    private val authService = AppServices.authService

    private val _state = MutableStateFlow(AppUiState())
    val state: StateFlow<AppUiState> = _state.asStateFlow()

    init {
        viewModelScope.launch {
            authService.session.collect { session ->
                _state.update {
                    it.copy(
                        token = session.token,
                        username = session.username,
                        currentClub = session.currentClub,
                        isAuthenticated = SessionGuardUtils.isAuthenticated(session.token),
                        isSessionLoaded = true
                    )
                }
                NetworkModule.updateAuthSession(session.token, session.username)
            }
        }
    }

    fun setCurrentClub(clubId: String?) {
        viewModelScope.launch {
            val current = _state.value
            authService.saveCurrentClub(current.token, current.username, clubId)
        }
    }

    fun logout() {
        viewModelScope.launch {
            authService.logout()
        }
    }
}

data class AppUiState(
    val token: String? = null,
    val username: String? = null,
    val currentClub: String? = null,
    val isAuthenticated: Boolean = false,
    val isSessionLoaded: Boolean = false
)
