package com.yorvana.data.billing

import android.app.Activity
import com.android.billingclient.api.BillingClient
import com.google.common.truth.Truth.assertThat
import com.yorvana.data.preferences.AppPreferences
import com.yorvana.data.preferences.AppPreferencesStore
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
import org.junit.Test

class BillingManagerImplTest {
    @Test
    fun `endConnection recreates client before next startConnection`() =
        runTest {
            val preferences =
                mockk<AppPreferencesStore> {
                    every { this@mockk.preferences } returns flowOf(AppPreferences())
                }
            val firstClient = mockk<BillingClient>(relaxed = true)
            val secondClient = mockk<BillingClient>(relaxed = true)
            val clients = ArrayDeque(listOf(firstClient, secondClient))

            val manager =
                BillingManagerImpl(
                    preferences = preferences,
                    coroutineScope = backgroundScope,
                    billingClientProvider = BillingClientProvider { clients.removeFirst() },
                )

            manager.endConnection()
            val launchResult = manager.launchPremiumPurchaseFlow(mockk<Activity>())
            manager.startConnection()

            assertThat(launchResult).isEqualTo(BillingLaunchResult.BillingUnavailable)
            verify { firstClient.endConnection() }
            verify { secondClient.startConnection(any()) }
        }
}
