package com.fabledsword.minstrel.auth.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fabledsword.minstrel.auth.AuthStore
import com.fabledsword.minstrel.cache.db.dao.AuthSessionDao
import com.fabledsword.minstrel.nav.Home
import com.fabledsword.minstrel.nav.Login
import com.fabledsword.minstrel.nav.ServerUrl
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Computes the initial startDestination for the root NavHost based on
 * persisted auth state. Sits on top of AuthSessionDao directly rather
 * than AuthStore's StateFlow because the StateFlow defaults to null
 * until Room's first async emission — we need a definitive answer
 * before drawing any nav graph.
 *
 *   - no row at all          → ServerUrl   (first launch)
 *   - row with baseUrl, no cookie → Login   (URL configured, not yet signed in)
 *   - row with cookie        → Home        (signed in)
 *
 * `startDestination` emits null while resolving (UI shows a spinner)
 * and then exactly one resolved value.
 */
@HiltViewModel
class AuthGateViewModel @Inject constructor(
    private val dao: AuthSessionDao,
) : ViewModel() {

    private val internal = MutableStateFlow<Any?>(null)
    val startDestination: StateFlow<Any?> = internal.asStateFlow()

    init {
        viewModelScope.launch {
            val row = dao.get()
            internal.value = when {
                row == null -> ServerUrl
                row.baseUrl == AuthStore.DEFAULT_BASE_URL && row.sessionCookie.isNullOrEmpty() ->
                    ServerUrl
                row.sessionCookie.isNullOrEmpty() -> Login
                else -> Home
            }
        }
    }
}
