package com.fabledsword.minstrel.shared.widgets.trackactions

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fabledsword.minstrel.models.PlaylistRef
import com.fabledsword.minstrel.playlists.data.PlaylistsRepository
import com.fabledsword.minstrel.shared.UiState
import com.fabledsword.minstrel.shared.asCacheFirstStateFlow
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Backs [AddToPlaylistSheet] with the caller's user-owned playlists.
 * System playlists (For You / Discover / etc.) are filtered out at
 * the repository layer — they're not appendable.
 */
@HiltViewModel
class AddToPlaylistViewModel @Inject constructor(
    repository: PlaylistsRepository,
) : ViewModel() {

    val uiState: StateFlow<UiState<List<PlaylistRef>>> = repository
        .observeUserPlaylists()
        .map { list ->
            if (list.isEmpty()) UiState.Empty else UiState.Success(list)
        }
        .onStart {
            // Best-effort refresh so the sheet reflects newly-created
            // playlists from another device. Cached list shows first;
            // refresh emission updates the state once Room reflects it.
            viewModelScope.launch {
                runCatching { repository.refreshList() }
            }
            emit(UiState.Loading)
        }
        .asCacheFirstStateFlow(viewModelScope)
}
