package com.radiola.ui.history

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.radiola.domain.model.Track
import com.radiola.domain.repository.RecognizedTrackRepository
import com.radiola.domain.repository.TrackHistoryRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import javax.inject.Inject

@HiltViewModel
class HistoryViewModel @Inject constructor(
    private val trackHistoryRepository: TrackHistoryRepository,
    private val recognizedTrackRepository: RecognizedTrackRepository
) : ViewModel() {

    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()

    private fun filtered(source: Flow<List<Track>>): StateFlow<List<Track>> =
        combine(source, _searchQuery) { tracks, query ->
            if (query.isBlank()) tracks else tracks.filter {
                it.artist.contains(query, ignoreCase = true) ||
                it.song.contains(query, ignoreCase = true)
            }
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

    // Треки эфира (как игрались на станциях)
    val history: StateFlow<List<Track>> = filtered(trackHistoryRepository.getHistory())

    // Распознанные через Shazam
    val recognized: StateFlow<List<Track>> = filtered(recognizedTrackRepository.getHistory())

    fun onSearchQueryChange(query: String) {
        _searchQuery.value = query
    }
}
