package de.krisenvorrat.app.data.db.dao

import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import de.krisenvorrat.app.data.db.KrisenvorratDatabase
import de.krisenvorrat.app.data.db.entity.SettingsEntity
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
internal class SettingsDaoTest {

    private lateinit var db: KrisenvorratDatabase
    private lateinit var dao: SettingsDao

    @Before
    fun setup() {
        db = Room.inMemoryDatabaseBuilder(
            ApplicationProvider.getApplicationContext(),
            KrisenvorratDatabase::class.java
        ).allowMainThreadQueries().build()
        dao = db.settingsDao()
    }

    @After
    fun teardown() {
        db.close()
    }

    @Test
    fun test_upsert_newKey_getValueReturnsValue() = runBlocking {
        // Given
        val setting = SettingsEntity(key = "theme", value = "dark")

        // When
        dao.upsert(setting)

        // Then
        val result = dao.getValue("theme")
        assertEquals("dark", result)
    }

    @Test
    fun test_getValue_unknownKey_returnsNull() = runBlocking {
        // Given / When
        val result = dao.getValue("nonexistent")

        // Then
        assertNull(result)
    }

    @Test
    fun test_upsert_existingKey_getAllReturnsOnlyOneEntry() = runBlocking {
        // Given
        dao.upsert(SettingsEntity(key = "theme", value = "dark"))

        // When
        dao.upsert(SettingsEntity(key = "theme", value = "light"))

        // Then
        val result = dao.getAll().first()
        assertEquals(1, result.size)
        assertEquals("light", result.first().value)
    }
}
