package com.iqser.red.service.peristence.v1.server.integration.utils;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

import java.util.concurrent.TimeUnit;

import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.micrometer.prometheus.PrometheusTimer;
import lombok.experimental.UtilityClass;

@UtilityClass
public class MetricValidationUtils {

    public static void validateMetric(PrometheusMeterRegistry registry, String name, int invocationCount, Integer time) {

        var metricOptional = registry.getMeters().stream().filter(m -> m.getId().getName().equalsIgnoreCase(name)).findAny();
        assertThat(metricOptional.isPresent()).isTrue();
        PrometheusTimer metric = (PrometheusTimer) metricOptional.get();
        assertThat(metric.count()).isGreaterThanOrEqualTo(invocationCount);
        if (time != null) {
            // for actually timing the method ...
            assertThat(metric.mean(TimeUnit.MILLISECONDS)).isGreaterThan(time);
        } else {
            // everything takes at least one nano-second - test the meter is correctly initialized
            assertThat(metric.mean(TimeUnit.NANOSECONDS)).isGreaterThan(1);
        }
    }

}
