package com.radiola.domain.usecase

import com.radiola.data.repository.StationTester
import com.radiola.domain.model.StationTestResult
import com.radiola.domain.repository.NowPlayingRepository
import com.radiola.domain.repository.StationRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import javax.inject.Inject

class TestStationsUseCase @Inject constructor(
    private val stationRepository: StationRepository,
    private val nowPlayingRepository: NowPlayingRepository,
    private val stationTester: StationTester
) {

    data class Progress(
        val current: Int,
        val total: Int,
        val result: StationTestResult? = null
    )

    operator fun invoke(): Flow<Progress> = flow {
        val stations = stationRepository.getStations().first()

        nowPlayingRepository.refreshNowPlaying()
        val nowPlayingMap = nowPlayingRepository.getAllNowPlaying().first()

        stations.forEachIndexed { index, station ->
            val result = withContext(Dispatchers.IO) {
                stationTester.test(station, nowPlayingMap[station.id])
            }
            emit(Progress(current = index + 1, total = stations.size, result = result))
        }
    }
}
