package com.tt.honeyDue.cache

import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.models.FeatureBenefit
import com.tt.honeyDue.models.Promotion
import com.tt.honeyDue.models.SubscriptionStatus
import com.tt.honeyDue.models.UpgradeTriggerData

/**
 * Thin facade over DataManager for subscription data.
 *
 * All state is delegated to DataManager (single source of truth).
 * This object exists for backwards compatibility with callers that
 * read subscription state (e.g. iOS SubscriptionCacheWrapper polling via Kotlin interop).
 *
 * For Compose UI code, prefer using DataManager StateFlows directly with collectAsState().
 */
object SubscriptionCache {
    /**
     * Current subscription status, delegated to DataManager.
     * For Compose callers, prefer: `val subscription by DataManager.subscription.collectAsState()`
     */
    val currentSubscription: SubscriptionCacheAccessor<SubscriptionStatus?>
        get() = SubscriptionCacheAccessor { DataManager.subscription.value }

    val upgradeTriggers: SubscriptionCacheAccessor<Map<String, UpgradeTriggerData>>
        get() = SubscriptionCacheAccessor { DataManager.upgradeTriggers.value }

    val featureBenefits: SubscriptionCacheAccessor<List<FeatureBenefit>>
        get() = SubscriptionCacheAccessor { DataManager.featureBenefits.value }

    val promotions: SubscriptionCacheAccessor<List<Promotion>>
        get() = SubscriptionCacheAccessor { DataManager.promotions.value }

    fun updateSubscriptionStatus(subscription: SubscriptionStatus) {
        DataManager.setSubscription(subscription)
    }

    fun updateUpgradeTriggers(triggers: Map<String, UpgradeTriggerData>) {
        DataManager.setUpgradeTriggers(triggers)
    }

    fun updateFeatureBenefits(benefits: List<FeatureBenefit>) {
        DataManager.setFeatureBenefits(benefits)
    }

    fun updatePromotions(promos: List<Promotion>) {
        DataManager.setPromotions(promos)
    }

    fun clear() {
        DataManager.setSubscription(null)
        DataManager.setUpgradeTriggers(emptyMap())
        DataManager.setFeatureBenefits(emptyList())
        DataManager.setPromotions(emptyList())
    }
}

/**
 * Simple accessor that provides .value to read from DataManager.
 * This preserves the `SubscriptionCache.currentSubscription.value` call pattern
 * used by existing callers (Kotlin code and iOS interop polling).
 */
class SubscriptionCacheAccessor<T>(private val getter: () -> T) {
    val value: T get() = getter()
}
