package com.ponzischeme89.memby.data

import android.content.Context
import androidx.test.core.app.ApplicationProvider
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner

@RunWith(RobolectricTestRunner::class)
class SettingsStoreProfileRemovalTest {
    @Test
    fun `automatic artwork style persists in the active profile`() = runBlocking {
        val context = ApplicationProvider.getApplicationContext<Context>()
        val store = SettingsStore(context)

        store.saveSession("https://artwork.example.test", "token", "art-user", "Ari", "server")
        store.setHomeArtworkStyle("poster")
        store.setHomeArtworkStyle("automatic")

        val settings = store.snapshot()
        assertEquals("automatic", settings.homeArtworkStyle)
        assertEquals(
            "automatic",
            settings.profiles.single { it.userId == "art-user" }.homeArtworkStyle,
        )
        store.removeProfile(settings.profiles.single { it.userId == "art-user" }.id)
    }

    @Test
    fun `ten minute reminder preference is persisted`() = runBlocking {
        val context = ApplicationProvider.getApplicationContext<Context>()
        val store = SettingsStore(context)

        store.setShowTenMinuteReminder(false)

        assertFalse(store.snapshot().showTenMinuteReminder)
    }

    @Test
    fun `removing profiles preserves other users and clears only an active session`() = runBlocking {
        val context = ApplicationProvider.getApplicationContext<Context>()
        val store = SettingsStore(context)

        store.saveSession("https://example.test", "token-a", "user-a", "Alex", "server")
        val alex = store.snapshot().profiles.single()
        store.saveSession("https://example.test", "token-b", "user-b", "Bailey", "server")
        val bailey = store.snapshot().profiles.single { it.userId == "user-b" }

        store.removeProfile(alex.id)
        val afterInactiveRemoval = store.snapshot()
        assertEquals(listOf(bailey.id), afterInactiveRemoval.profiles.map { it.id })
        assertTrue(afterInactiveRemoval.isSignedIn)
        assertEquals("user-b", afterInactiveRemoval.userId)

        store.removeProfile(bailey.id)
        val afterActiveRemoval = store.snapshot()
        assertTrue(afterActiveRemoval.profiles.isEmpty())
        assertFalse(afterActiveRemoval.isSignedIn)
    }
}
