package dev.lions.user.manager.resource;

import dev.lions.user.manager.client.KeycloakAdminClient;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * Resource REST pour health et readiness
 */
@Path("/api/health")
@Produces(MediaType.APPLICATION_JSON)
@Slf4j
public class HealthResourceEndpoint {

    @Inject
    KeycloakAdminClient keycloakAdminClient;

    @GET
    @Path("/keycloak")
    public Map<String, Object> getKeycloakHealth() {
        Map<String, Object> health = new HashMap<>();

        try {
            // Vérifier simplement que le client est initialisé (pas d'appel réel à Keycloak)
            boolean initialized = keycloakAdminClient.getInstance() != null;
            health.put("status", initialized ? "UP" : "DOWN");
            health.put("connected", initialized);
            health.put("message", initialized ? "Client Keycloak initialisé" : "Client non initialisé");
            health.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            log.error("Erreur health check Keycloak", e);
            health.put("status", "ERROR");
            health.put("connected", false);
            health.put("error", e.getMessage());
            health.put("timestamp", System.currentTimeMillis());
        }

        return health;
    }

    @GET
    @Path("/status")
    public Map<String, Object> getServiceStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("service", "lions-user-manager-server");
        status.put("version", "1.0.0");
        status.put("status", "UP");
        status.put("timestamp", System.currentTimeMillis());

        // Health Keycloak
        try {
            boolean keycloakConnected = keycloakAdminClient.isConnected();
            status.put("keycloak", keycloakConnected ? "CONNECTED" : "DISCONNECTED");
        } catch (Exception e) {
            status.put("keycloak", "ERROR");
            status.put("keycloakError", e.getMessage());
        }

        return status;
    }
}
