package com.fabledsword.minstrel.connectivity

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map

/**
 * Emits once each time server health RETURNS to [ServerHealth.Healthy]
 * after the collector subscribed — the StateFlow's replayed current value
 * is dropped, so only genuine down→up transitions fire (a screen that
 * subscribes while already Healthy doesn't double-load).
 *
 * This is the screen-level half of the recovery idiom the app-lifetime
 * singletons (SyncController / MutationReplayer / DiagnosticsUploader)
 * already use: a ViewModel collects this in its viewModelScope and re-runs
 * its load, so a surface that failed while the server was unreachable
 * heals itself the moment connectivity returns instead of sitting in the
 * failed state until a manual pull-to-refresh.
 */
fun NetworkStatusController.recoveries(): Flow<Unit> = state
    .map { it == ServerHealth.Healthy }
    .distinctUntilChanged()
    .drop(1)
    .filter { it }
    .map { }
