package com.onthelevel.core.billing

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * Pro entitlement state (BRIEF.md §Monetization). One permanent non-consumable
 * product; no subscription.
 */
data class Entitlement(
    val isPro: Boolean,
    val source: Source,
) {
    enum class Source {
        /** No confirmation yet — the default, and always safe: free tools are complete. */
        NONE,
        /** Confirmed by Google Play this session. */
        PLAY_CONFIRMED,
        /** Previously Play-confirmed, restored from local cache (offline job-site use). */
        CACHED,
    }

    companion object {
        val FREE = Entitlement(isPro = false, source = Source.NONE)
    }
}

/**
 * The ONLY doorway between billing and the rest of the app. Feature code observes
 * [entitlement]; nothing outside core/billing may touch Play Billing types
 * (AUDIT.md: Pro boundary containment).
 */
interface ProEntitlementRepository {
    val entitlement: StateFlow<Entitlement>

    /** Re-query owned purchases when possible (app resume, purchase flow completion). */
    suspend fun refresh()
}

/**
 * Scaffold stand-in: everyone is free tier. Replaced by the Play Billing
 * implementation, which must:
 *  - initialize lazily/async — free tools never block on Play services
 *  - cache a Play-confirmed entitlement in DataStore for offline use
 *  - never grant from an arbitrary preference value or a PENDING purchase
 */
class StubProEntitlementRepository : ProEntitlementRepository {
    private val state = MutableStateFlow(Entitlement.FREE)
    override val entitlement: StateFlow<Entitlement> = state.asStateFlow()
    override suspend fun refresh() = Unit
}

// TODO(billing): PlayBillingEntitlementRepository against the declared billing-ktx
// dependency, product id "on_the_level_pro", per the contract above.
