package com.github.nullptroma.wallenc.infrastructure.android.db.app.repository

import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.nullptroma.wallenc.domain.vault.model.YandexAccount
import com.github.nullptroma.wallenc.infrastructure.android.db.app.AppDb
import kotlinx.coroutines.Dispatchers
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)
class YandexAccountRepositoryTest {

    private lateinit var db: AppDb
    private lateinit var repository: YandexAccountRepository

    @Before
    fun setUp() {
        val context = ApplicationProvider.getApplicationContext<android.content.Context>()
        db = Room.inMemoryDatabaseBuilder(context, AppDb::class.java).build()
        repository = YandexAccountRepository(
            dao = db.yandexAccountDao,
            ioDispatcher = Dispatchers.IO,
        )
    }

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

    @Test
    fun insertAndLoadByVaultUuid() = runBlocking {
        val account = YandexAccount(
            vaultUuid = "vault-1",
            yandexUserId = "user-1",
            email = "test@yandex.ru",
            oauthToken = "token-abc",
        )
        repository.insert(account)
        val loaded = repository.getByVaultUuid("vault-1")
        assertEquals(account, loaded)
    }

    @Test
    fun updateCredentialsChangesToken() = runBlocking {
        repository.insert(
            YandexAccount(
                vaultUuid = "vault-2",
                yandexUserId = "user-2",
                email = "old@yandex.ru",
                oauthToken = "old-token",
            ),
        )
        repository.updateCredentials("vault-2", "new@yandex.ru", "new-token")
        val loaded = repository.getByVaultUuid("vault-2")
        assertEquals("new@yandex.ru", loaded?.email)
        assertEquals("new-token", loaded?.oauthToken)
    }

    @Test
    fun deleteByVaultUuidRemovesRow() = runBlocking {
        repository.insert(
            YandexAccount(
                vaultUuid = "vault-3",
                yandexUserId = "user-3",
                email = "x@yandex.ru",
                oauthToken = "t",
            ),
        )
        repository.deleteByVaultUuid("vault-3")
        assertNull(repository.getByVaultUuid("vault-3"))
    }
}
