package ru.forbion.f7cloud.feature.talknative

import android.content.Context
import android.util.Log
import ru.f7cloud.talk.application.F7cloudTalkApplication
import ru.f7cloud.talk.f7cloud.F7TalkUserSync
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import ru.forbion.f7cloud.core.auth.AuthSession

/**
 * Ensures talk-android [ru.f7cloud.talk.data.user.model.User] exists for F7cloud sessions.
 * Required before native [ru.f7cloud.talk.activities.CallActivity] can run.
 *
 * suspend (IO) — раньше был runBlocking на main (старт приложения и путь звонка),
 * что давало ANR-риск из аудита (C4/п.7).
 */
object TalkVendorUserSync {
    private const val TAG = "TalkVendorUserSync"

    suspend fun ensureUser(context: Context, session: AuthSession): Boolean {
        if (context.applicationContext !is F7cloudTalkApplication) {
            Log.w(TAG, "Application is not F7cloudTalkApplication, skip sync")
            return false
        }
        return withContext(Dispatchers.IO) {
            runCatching {
                F7TalkUserSync.get().ensureUser(
                    serverUrl = session.serverUrl,
                    username = session.username,
                    appPassword = session.appPassword,
                    davUserId = session.davUserId,
                )
            }
                .onFailure { Log.w(TAG, "Talk user sync failed: ${it.message}", it) }
                .getOrNull() != null
        }
    }
}
