package dev.lions.user.manager.resource;

import dev.lions.user.manager.client.KeycloakAdminClient;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Readiness;

/**
 * Health check pour Keycloak
 */
@Readiness
@Slf4j
public class KeycloakHealthCheck implements HealthCheck {

    @Inject
    KeycloakAdminClient keycloakAdminClient;

    @Override
    public HealthCheckResponse call() {
        try {
            boolean connected = keycloakAdminClient.isConnected();

            if (connected) {
                return HealthCheckResponse.builder()
                    .name("keycloak-connection")
                    .up()
                    .withData("status", "connected")
                    .withData("message", "Keycloak est disponible")
                    .build();
            } else {
                return HealthCheckResponse.builder()
                    .name("keycloak-connection")
                    .down()
                    .withData("status", "disconnected")
                    .withData("message", "Keycloak n'est pas disponible")
                    .build();
            }
        } catch (Exception e) {
            log.error("Erreur lors du health check Keycloak", e);
            return HealthCheckResponse.builder()
                .name("keycloak-connection")
                .down()
                .withData("status", "error")
                .withData("message", e.getMessage())
                .build();
        }
    }
}
