package com.doctate.watch.sync

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

/**
 * Owns the [SyncState] StateFlow. Written by [SyncWorkerLoop], read by
 * the UI. Decoupled from the Service / Application class so JVM tests
 * can drive the worker against a fresh provider.
 */
class SyncStateProvider {
    private val _state = MutableStateFlow(SyncState())
    val state: StateFlow<SyncState> = _state.asStateFlow()

    fun setIdle(queueLen: Int, pendingCaseIds: Set<String>) {
        _state.update { it.copy(phase = WorkerPhase.Idle, queueLen = queueLen, pendingCaseIds = pendingCaseIds) }
    }

    fun setUploading(queueLen: Int, pendingCaseIds: Set<String>) {
        _state.update { it.copy(phase = WorkerPhase.Uploading, queueLen = queueLen, pendingCaseIds = pendingCaseIds) }
    }

    fun setPolling(queueLen: Int, pendingCaseIds: Set<String>) {
        _state.update { it.copy(phase = WorkerPhase.Polling, queueLen = queueLen, pendingCaseIds = pendingCaseIds) }
    }

    fun recordSuccess(at: Long) {
        _state.update { it.copy(lastSuccessAt = at, lastFailureReason = null) }
    }

    fun recordFailure(at: Long, reason: String) {
        _state.update { it.copy(lastFailureAt = at, lastFailureReason = reason) }
    }
}
