package space.nstart.pcp_tgu_service.service

import io.micrometer.core.instrument.Counter
import io.micrometer.core.instrument.Gauge
import io.micrometer.core.instrument.MeterRegistry
import org.springframework.stereotype.Component
import java.util.concurrent.atomic.AtomicInteger

/**
 * Метрики доступности Ordinis/НСИ для alerting по последней попытке синхронизации.
 */
@Component
class OrdinisAvailabilityMetrics(
    meterRegistry: MeterRegistry
) {
    private val unavailableGaugeValue = AtomicInteger(0)
    private val unavailableCounter = Counter.builder(UNAVAILABLE_TOTAL)
        .description("Total Ordinis classifier fetch failures detected by pcp-tgu-service")
        .register(meterRegistry)

    init {
        Gauge.builder(UNAVAILABLE, unavailableGaugeValue) { value -> value.get().toDouble() }
            .description("1 when the last Ordinis classifier fetch failed, 0 after a successful fetch")
            .register(meterRegistry)
    }

    fun markAvailable() {
        unavailableGaugeValue.set(0)
    }

    fun markUnavailable() {
        unavailableGaugeValue.set(1)
        unavailableCounter.increment()
    }

    companion object {
        const val UNAVAILABLE = "pcp_tgu_ordinis_unavailable"
        const val UNAVAILABLE_TOTAL = "pcp_tgu_ordinis_unavailable_total"
    }
}
