package ru.forbion.f7cloud.feature.talk

import android.content.Context
import android.content.Intent
import ru.forbion.f7cloud.core.auth.AuthStore
import ru.forbion.f7cloud.core.push.PushIntents

/** Handles Android Direct Share into Talk. */
object TalkShareTarget {
    fun handleShare(context: Context, intent: Intent): String? {
        if (intent.action != Intent.ACTION_SEND) return null
        val text = intent.getStringExtra(Intent.EXTRA_TEXT)?.trim().orEmpty()
        if (text.isEmpty()) return null
        val session = AuthStore(context).load() ?: return null
        // Open Talk tab; message prefill via URL fragment (handled by AppScaffold).
        return "${session.serverUrl.trimEnd('/')}/apps/spreed/#share=${java.net.URLEncoder.encode(text, "UTF-8")}"
    }

    fun launch(context: Context, intent: Intent) {
        val url = handleShare(context, intent) ?: return
        val launch = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return
        launch.putExtra(PushIntents.EXTRA_OPEN_URL, url)
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
        context.startActivity(launch)
    }
}
