package dev.lions.unionflow.server.resource;

import dev.lions.unionflow.server.api.dto.communication.request.SendMessageRequest;
import dev.lions.unionflow.server.api.dto.communication.response.MessageResponse;
import dev.lions.unionflow.server.service.MessageService;
import dev.lions.unionflow.server.service.support.SecuriteHelper;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.jboss.logging.Logger;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Resource REST pour la gestion des messages
 *
 * @author UnionFlow Team
 * @version 1.0
 * @since 2026-03-16
 */
@Path("/api/messages")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Tag(name = "Communication", description = "Gestion des conversations et messages")
@RolesAllowed({"ADMIN", "SUPER_ADMIN", "MEMBRE", "ADMIN_ORGANISATION"})
public class MessageResource {

    private static final Logger LOG = Logger.getLogger(MessageResource.class);

    @Inject
    MessageService messageService;

    @Inject
    SecuriteHelper securiteHelper;

    /**
     * Récupère les messages d'une conversation
     */
    @GET
    @Operation(summary = "Lister les messages d'une conversation")
    @APIResponse(responseCode = "200", description = "Liste des messages")
    @APIResponse(responseCode = "404", description = "Conversation non trouvée")
    public Response getMessages(
        @Parameter(description = "ID de la conversation", required = true)
        @QueryParam("conversationId") UUID conversationId,
        @Parameter(description = "Nombre maximum de messages")
        @QueryParam("limit") @DefaultValue("50") int limit
    ) {
        if (conversationId == null) {
            return Response.status(Response.Status.BAD_REQUEST)
                .entity(Map.of("error", "conversationId requis"))
                .build();
        }

        UUID membreId = securiteHelper.resolveMembreId();
        List<MessageResponse> messages = messageService.getMessages(conversationId, membreId, limit);
        return Response.ok(messages).build();
    }

    /**
     * Envoie un message
     */
    @POST
    @Operation(summary = "Envoyer un message")
    @APIResponse(responseCode = "201", description = "Message envoyé")
    @APIResponse(responseCode = "400", description = "Données invalides")
    @APIResponse(responseCode = "404", description = "Conversation non trouvée")
    public Response sendMessage(@Valid SendMessageRequest request) {
        UUID senderId = securiteHelper.resolveMembreId();
        MessageResponse message = messageService.sendMessage(request, senderId);
        return Response.status(Response.Status.CREATED).entity(message).build();
    }

    /**
     * Édite un message
     */
    @PUT
    @Path("/{id}")
    @Operation(summary = "Éditer un message")
    @APIResponse(responseCode = "200", description = "Message édité")
    @APIResponse(responseCode = "404", description = "Message non trouvé")
    public Response editMessage(
        @PathParam("id") UUID messageId,
        Map<String, String> body
    ) {
        String newContent = body.get("content");
        if (newContent == null || newContent.isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                .entity(Map.of("error", "content requis"))
                .build();
        }

        UUID senderId = securiteHelper.resolveMembreId();
        MessageResponse message = messageService.editMessage(messageId, senderId, newContent);
        return Response.ok(message).build();
    }

    /**
     * Supprime un message
     */
    @DELETE
    @Path("/{id}")
    @Operation(summary = "Supprimer un message")
    @APIResponse(responseCode = "204", description = "Message supprimé")
    @APIResponse(responseCode = "404", description = "Message non trouvé")
    public Response deleteMessage(@PathParam("id") UUID messageId) {
        UUID senderId = securiteHelper.resolveMembreId();
        messageService.deleteMessage(messageId, senderId);
        return Response.noContent().build();
    }
}
