package cloud.nstart.terravault.ordinis.outbox;

import cloud.nstart.terravault.ordinis.domain.outbox.OutboxEventRepository;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.annotation.PostConstruct;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * Gauges:
 * <ul>
 *   <li>{@code ordinis_outbox_pending_events} — unpublished без DLQ. Растёт ⇒
 *       poller не успевает либо Kafka недоступна.</li>
 *   <li>{@code ordinis_outbox_dlq_size} — события в DLQ. Любое значение &gt; 0 ⇒
 *       требуется ручной разбор (orphan topic, ACL, broken payload).</li>
 * </ul>
 */
@Component
@ConditionalOnProperty(name = "ordinis.outbox.enabled", havingValue = "true", matchIfMissing = false)
public class OutboxLagGauge {

  private final OutboxEventRepository repository;
  private final MeterRegistry meterRegistry;

  public OutboxLagGauge(OutboxEventRepository repository, MeterRegistry meterRegistry) {
    this.repository = repository;
    this.meterRegistry = meterRegistry;
  }

  @PostConstruct
  void register() {
    Gauge.builder("ordinis_outbox_pending_events", repository,
            r -> (double) r.countPending())
        .description("Количество outbox events ожидающих публикацию (без DLQ)")
        .register(meterRegistry);

    Gauge.builder("ordinis_outbox_dlq_size", repository,
            r -> (double) r.countByDlqAtIsNotNull())
        .description("Количество outbox events в DLQ (требуют ручного разбора)")
        .register(meterRegistry);
  }
}
