package app.closer.ui.play

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.billing.CouplePremiumChecker
import app.closer.domain.usecase.GameSessionManager
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

@HiltViewModel
class PlayHubViewModel @Inject constructor(
    premiumChecker: CouplePremiumChecker,
    private val gameSessionManager: GameSessionManager
) : ViewModel() {
    val hasPremium: StateFlow<Boolean> = premiumChecker.isPremium()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)

    // Default true so paired users never see an invite redirect flash while this loads.
    private val _isPaired = MutableStateFlow(true)
    val isPaired: StateFlow<Boolean> = _isPaired.asStateFlow()

    init {
        viewModelScope.launch {
            val uid = gameSessionManager.currentUserId
            val paired = uid != null &&
                runCatching { gameSessionManager.getCoupleForUser(uid) }.getOrNull() != null
            _isPaired.value = paired
        }
    }
}
