package com.fabledsword.minstrel.shared.widgets

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fabledsword.minstrel.auth.AuthController
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

private const val SHARE_STOP_TIMEOUT_MS = 5_000L

/**
 * Backs [MainAppBarActions] with the current user's admin flag so the
 * overflow "Admin" item appears for every admin without each shell
 * screen having to plumb the value through. Sourced from
 * [AuthController.currentUser] so it stays live across sign-in,
 * sign-out, and role changes pushed via rehydration.
 */
@HiltViewModel
class AppBarActionsViewModel @Inject constructor(
    authController: AuthController,
) : ViewModel() {
    val isAdmin: StateFlow<Boolean> = authController.currentUser
        .map { it?.isAdmin == true }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS),
            initialValue = false,
        )
}
