import Foundation /// Encapsulates the premium status sync state machine. /// Extracted from ContentView to be independently testable. @MainActor final class PremiumSyncService { /// Injectable for testing — defaults to real StoreKit check. var hasActiveSubscription: () async -> Bool = { await StoreManager.hasActiveSubscription() } /// Determine whether the user should be premium after a sync. /// /// Rules: /// - Active subscription found → always return `true` (upgrade). /// - No subscription, currently free → return `false`. /// - No subscription, currently premium, **cold launch** → return `false` /// (subscription likely expired between sessions). /// - No subscription, currently premium, **foreground activation** → return `true` /// (StoreKit `currentEntitlements` can return empty for a few seconds immediately /// after a purchase while the receipt propagates; never downgrade mid-session). func sync(currentIsPremium: Bool, isColdLaunch: Bool) async -> Bool { let active = await hasActiveSubscription() switch (active, currentIsPremium, isColdLaunch) { case (true, _, _): return true case (false, false, _): return false case (false, true, true): return false // Subscription expired → downgrade on cold launch case (false, true, false): return true // Keep premium on foreground (timing protection) } } }