package ru.fincode.tsudesk.feature.news.domain.usecase

import androidx.paging.PagingData
import androidx.paging.filter
import androidx.paging.cachedIn
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
import ru.fincode.tsudesk.feature.news.domain.model.NewsItem
import ru.fincode.tsudesk.feature.news.domain.repository.NewsRepository
import javax.inject.Inject

class GetNewsPagingUseCase @Inject constructor(
    private val repository: NewsRepository
) {

    /**
     * @param queryFlow поток поискового запроса
     * @param scope scope для cachedIn
     */
    operator fun invoke(
        queryFlow: Flow<String>,
        scope: CoroutineScope
    ): Flow<PagingData<NewsItem>> {

        val pagingBase = repository
            .paging()
            .cachedIn(scope)

        val debouncedQuery = queryFlow
            .map(String::trim)
            .debounce(300)
            .distinctUntilChanged()

        return combine(pagingBase, debouncedQuery) { paging, query ->
            if (query.isBlank()) {
                paging
            } else {
                paging.filter {
                    it.title.contains(query, ignoreCase = true)
                }
            }
        }
    }
}