package dev.lions.user.manager.resource;

import dev.lions.user.manager.client.KeycloakAdminClient;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.annotation.security.RolesAllowed;
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 jakarta.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;

import java.util.List;

/**
 * Ressource REST pour la gestion des realms Keycloak
 */
@Path("/api/realms")
@Tag(name = "Realms", description = "Gestion des realms Keycloak")
@Slf4j
public class RealmResource {

    @Inject
    KeycloakAdminClient keycloakAdminClient;

    @Inject
    SecurityIdentity securityIdentity;

    @GET
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    @Operation(summary = "Lister tous les realms", description = "Récupère la liste de tous les realms disponibles dans Keycloak")
    @APIResponses({
        @APIResponse(responseCode = "200", description = "Liste des realms"),
        @APIResponse(responseCode = "500", description = "Erreur serveur")
    })
    @RolesAllowed({"admin", "user_manager", "user_viewer", "role_manager", "role_viewer"})
    public Response getAllRealms() {
        log.info("GET /api/realms/list");

        try {
            List<String> realms = keycloakAdminClient.getAllRealms();
            log.info("Récupération réussie: {} realms trouvés", realms.size());
            return Response.ok(realms).build();
        } catch (Exception e) {
            log.error("Erreur lors de la récupération des realms", e);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(new ErrorResponse("Erreur lors de la récupération des realms: " + e.getMessage()))
                .build();
        }
    }

    /**
     * Classe interne pour les réponses d'erreur
     */
    public static class ErrorResponse {
        private String message;

        public ErrorResponse(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
}

