package com.radiola.ui.stations

import com.radiola.domain.model.Station
import com.radiola.domain.usecase.GetStationsUseCase
import com.radiola.domain.usecase.PlayStationUseCase
import com.radiola.domain.usecase.ToggleFavoriteUseCase
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test

@OptIn(ExperimentalCoroutinesApi::class)
class StationsViewModelTest {

    private val testDispatcher = StandardTestDispatcher()
    private val getStationsUseCase: GetStationsUseCase = mockk()
    private val playStationUseCase: PlayStationUseCase = mockk(relaxed = true)
    private val toggleFavoriteUseCase: ToggleFavoriteUseCase = mockk(relaxed = true)

    @Before
    fun setup() {
        Dispatchers.setMain(testDispatcher)
        every { getStationsUseCase() } returns flowOf(
            listOf(
                Station(1, "Record", "rr", "", "", "Trans", listOf("trans"), 0),
                Station(2, "Deep", "deep", "", "", "House", listOf("house"), 1)
            )
        )
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
    }

    @Test
    fun `stations filtered by search query`() = runTest {
        val viewModel = StationsViewModel(getStationsUseCase, playStationUseCase, toggleFavoriteUseCase)
        advanceUntilIdle()

        viewModel.onSearchQueryChange("Record")
        advanceUntilIdle()

        assertEquals(1, viewModel.stations.value.size)
        assertEquals("Record", viewModel.stations.value[0].name)
    }

    @Test
    fun `playStation calls use case`() = runTest {
        val viewModel = StationsViewModel(getStationsUseCase, playStationUseCase, toggleFavoriteUseCase)
        val station = Station(1, "Record", "rr", "", "", "", emptyList(), 0)

        viewModel.playStation(station)
        advanceUntilIdle()

        coVerify { playStationUseCase(station) }
    }
}
