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

import com.magistr.app.config.tenant.TenantConfig;
import com.magistr.app.config.tenant.TenantRoutingDataSource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class TenantReadinessHealthIndicatorTest {

    private static final Instant NOW = Instant.parse("2026-07-15T10:00:00Z");

    @Test
    void зарегистрированПодИменемTenantReadiness() {
        Component annotation = TenantReadinessHealthIndicator.class.getAnnotation(Component.class);

        assertEquals("tenantReadiness", annotation.value());
    }

    @Test
    void возвращаетТолькоАгрегированныеДанные() {
        Clock clock = Clock.fixed(NOW, ZoneOffset.UTC);
        TenantReadinessRegistry registry = new TenantReadinessRegistry(
                clock,
                "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8));
        TenantConfig tenant = new TenantConfig(
                "Secret university",
                "alpha",
                "jdbc:postgresql://private-host/private-db",
                "private-user",
                "private-password");
        registry.replaceDesired(List.of(tenant));
        registry.markMigrationSucceeded(tenant);
        registry.markConnectivity("alpha", true);

        TenantDatabaseHealthMonitor monitor = new TenantDatabaseHealthMonitor(
                registry,
                new TenantRoutingDataSource(),
                1,
                Duration.ofSeconds(1),
                Duration.ofSeconds(30),
                clock);
        try {
            TenantReadinessHealthIndicator indicator = new TenantReadinessHealthIndicator(registry, monitor);
            TenantReadinessRegistry.AggregateReadiness readiness = indicator.readiness();

            assertEquals(Status.UP, indicator.health().getStatus());
            assertTrue(readiness.ready());
            assertEquals("ГОТОВ", readiness.status());
            assertEquals(1, readiness.desiredTenants());
            assertEquals(1, readiness.readyTenants());
            assertEquals(0, readiness.unavailableTenants());
            assertFalse(readiness.configurationFailure());
        } finally {
            monitor.close();
        }
    }
}
