package com.ponzischeme89.memby.update

import com.ponzischeme89.memby.data.SettingsStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * Writes every refusal to disk the moment it arrives.
 *
 * It is owned by the service locator rather than by a screen because the refusal lands on
 * whichever request happened to be in flight — the status poll, a home refresh, a sign-in
 * — and any of those can be running while nothing that knows about update policy is
 * composed. It is also the half that survives a restart: the gateway announces the
 * retirement exactly once, on the 401 that deletes the session, and every 401 after that
 * is an ordinary missing session carrying no header at all.
 */
class RequiredUpdateGuard(
    private val settings: SettingsStore,
    scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO),
) {
    init {
        scope.launch {
            RequiredUpdateSignal.required.collect { settings.markRequiredUpdate(it) }
        }
    }
}
