package com.yorvana.data.billing

import android.app.Activity
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * A controllable [BillingManager] test double for use in unit and integration tests.
 *
 * Unlike a mock, this class manages its own [isPremium] [StateFlow] so that tests can
 * observe reactive updates exactly as production code would.
 *
 * Set [restoreDeferred] to a [CompletableDeferred] to suspend [restorePurchases] until
 * it is completed — useful for testing re-entrancy guards.
 */
class FakeBillingManager :
    BillingManager,
    DebugBillingActions {
    val premiumState = MutableStateFlow(false)
    override val isPremium: StateFlow<Boolean> = premiumState.asStateFlow()

    val pendingState = MutableStateFlow(false)
    override val hasPendingPurchase: StateFlow<Boolean> = pendingState.asStateFlow()

    var launchResult: BillingLaunchResult = BillingLaunchResult.Success
    var restoreResult: RestoreResult = RestoreResult.Success(hadPurchase = false)
    var restoreDeferred: CompletableDeferred<RestoreResult>? = null

    var startConnectionCalled = false
    var endConnectionCalled = false
    var refreshCalled = false
    var launchPurchaseFlowCallCount = 0
    var lastLaunchActivity: Activity? = null

    override fun startConnection() {
        startConnectionCalled = true
    }

    override fun endConnection() {
        endConnectionCalled = true
    }

    override fun refresh() {
        refreshCalled = true
    }

    override fun launchPremiumPurchaseFlow(activity: Activity): BillingLaunchResult {
        launchPurchaseFlowCallCount++
        lastLaunchActivity = activity
        return launchResult
    }

    override suspend fun restorePurchases(): RestoreResult = restoreDeferred?.await() ?: restoreResult

    override suspend fun simulatePurchaseSuccess() {
        premiumState.value = true
    }

    override suspend fun resetBillingState() {
        premiumState.value = false
    }
}
