package ru.forbion.f7cloud.feature.talknative

import android.content.Context
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.auth.AuthStore

/**
 * Hooks F7cloud auth into talk-android runtime (User DB, capabilities) for native WebRTC.
 */
object TalkVendorBootstrap {
    private const val TAG = "TalkVendorBootstrap"
    private val warmupScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)

    /** Прогрев vendor-юзера на старте — в фоне (раньше блокировал main в Application.onCreate). */
    fun onApplicationCreate(context: Context) {
        if (!TalkNativeConfig.bootstrapVendorRuntime) return
        val appContext = context.applicationContext
        warmupScope.launch {
            val session = AuthStore(appContext).load() ?: return@launch
            runCatching { TalkVendorUserSync.ensureUser(appContext, session) }
                .onFailure { Log.w(TAG, "Talk user sync failed: ${it.message}") }
        }
    }

    suspend fun ensureSessionReady(context: Context, session: AuthSession): Boolean {
        if (!TalkNativeConfig.bootstrapVendorRuntime) return true
        return runCatching { TalkVendorUserSync.ensureUser(context, session) }
            .onFailure { Log.w(TAG, "Talk user sync failed: ${it.message}") }
            .getOrDefault(false)
    }
}
