package com.divya.hardinfo.viewmodel

import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.divya.hardinfo.data.HardwareRepository
import com.divya.hardinfo.model.Category
import com.divya.hardinfo.model.HardwareItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.*
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations

@ExperimentalCoroutinesApi
class HardwareViewModelTest {

    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    @Mock
    private lateinit var repository: HardwareRepository

    private lateinit var viewModel: HardwareViewModel

    private val testDispatcher = UnconfinedTestDispatcher()

    @Before
    fun setup() {
        MockitoAnnotations.openMocks(this)
        Dispatchers.setMain(testDispatcher)
        
        // Use the mocked repository
        val application = mock(android.app.Application::class.java)
        viewModel = HardwareViewModel(application, repository)
    }

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

    @Test
    fun `searchItems updates searchResults with filtered items`() = runTest {
        val query = "Intel"
        val mockResults = listOf(
            HardwareItem("1", "Intel Core i9", "CPU", "Desc", "Specs", "Func", "Use", "img", false)
        )
        
        `when`(repository.searchItems(query)).thenReturn(mockResults)
        
        viewModel.search(query)
        testDispatcher.scheduler.advanceUntilIdle()
        
        assertEquals(mockResults, viewModel.searchResults.value)
    }
    
    @Test
    fun `loadCategories loads data on init`() = runTest {
        // ViewModel init calls loadCategories, which calls repository.getCategories()
        // verify that repository.getCategories() was invoked
        verify(repository).getCategories()
    }
    
    @Test
    fun `toggleFavorite calls repository`() = runTest {
        val item = HardwareItem("1", "Hardware", "Cat", "Desc", "Specs", "Func", "Use", "img", false)
        
        viewModel.toggleFavorite(item)
        testDispatcher.scheduler.advanceUntilIdle()
        
        verify(repository).toggleFavorite(item)
    }
}
