package wang.yaojia.webterm.push

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton

/**
 * The A31 [PushTokenSink] implementation: a rotated FCM registration token (from
 * [FcmService.onNewToken]) is re-registered with EVERY paired host via [PushRegistrar] — the self-heal
 * path (plan §4.5). `@Binds` in `di/PushModule` publishes this as the concrete `PushTokenSink`, so the
 * `Optional<PushTokenSink>` [FcmService] injects becomes present.
 *
 * [onTokenRefreshed] is a synchronous fire-and-forget hook (the FCM callback is not `suspend`), so it
 * launches the best-effort fan-out on a long-lived app scope. [PushRegistrar.registerAllHosts] already
 * swallows per-host failures and re-reads [HostStore][wang.yaojia.webterm.hostregistry.HostStore] on
 * every pass, so nothing here retains the token or the host list.
 */
@Singleton
public class PushRegistrarTokenSink @Inject constructor(
    private val registrar: PushRegistrar,
) : PushTokenSink {

    /** App-lifetime scope for the fire-and-forget re-registration (survives the FCM callback returning). */
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

    override fun onTokenRefreshed(token: String) {
        scope.launch { registrar.registerAllHosts(token) }
    }
}
