package com.tt.honeyDue.storage

/**
 * Token storage that provides a unified interface for accessing platform-specific
 * persistent storage. This allows tokens to persist across app restarts.
 */
object TokenStorage {
    private var tokenManager: TokenManager? = null
    private var cachedToken: String? = null

    /**
     * Initialize TokenStorage with a platform-specific TokenManager.
     * This should be called once during app initialization.
     */
    fun initialize(manager: TokenManager) {
        tokenManager = manager
        // Load cached token from persistent storage
        cachedToken = manager.getToken()
    }

    private fun ensureInitialized() {
        if (tokenManager == null) {
            tokenManager = getPlatformTokenManager()
            cachedToken = tokenManager?.getToken()
        }
    }

    fun saveToken(token: String) {
        ensureInitialized()
        cachedToken = token
        tokenManager?.saveToken(token)
    }

    fun getToken(): String? {
        ensureInitialized()
        // Always read from storage to avoid stale cache issues
        // (DataManager.setAuthToken updates tokenManager directly, bypassing our cachedToken)
        cachedToken = tokenManager?.getToken()
        return cachedToken
    }

    fun clearToken() {
        ensureInitialized()
        cachedToken = null
        tokenManager?.clearToken()
    }

    fun hasToken(): Boolean = getToken() != null
}

/**
 * Platform-specific function to get the default TokenManager instance.
 * For platforms that don't require context (web, iOS, JVM), returns singleton.
 * For Android, must be initialized via initialize() method before use.
 */
internal expect fun getPlatformTokenManager(): TokenManager?
