package com.magistr.app.config.tenant.health;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * Агрегированный индикатор readiness без раскрытия доменов и реквизитов tenant-БД.
 */
@Component("tenantReadiness")
public class TenantReadinessHealthIndicator implements HealthIndicator {

    private final TenantReadinessRegistry registry;
    private final TenantDatabaseHealthMonitor monitor;

    public TenantReadinessHealthIndicator(TenantReadinessRegistry registry,
                                          TenantDatabaseHealthMonitor monitor) {
        this.registry = Objects.requireNonNull(registry, "Реестр готовности обязателен");
        this.monitor = Objects.requireNonNull(monitor, "Монитор tenant-БД обязателен");
    }

    @Override
    public Health health() {
        return readiness().ready()
                ? Health.up().build()
                : Health.down().build();
    }

    public TenantReadinessRegistry.AggregateReadiness readiness() {
        return registry.aggregate(monitor.maxStaleness());
    }

    public boolean isReady() {
        return readiness().ready();
    }
}
