package agent

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/api/dto/converter"
)

// ReactionHandler owns reaction lookup and mutation endpoints for agents.
type ReactionHandler struct {
	auth   AgentAuthenticator
	store  ReactionStore
	fanout ReactionFanout
}

// Get returns the current reaction aggregates for one visible message.
func (h *ReactionHandler) Get(c *gin.Context) {
	agent, ok := authenticate(c, h.auth)
	if !ok {
		return
	}
	var request dto.AgentReactionGetRequest
	if !bindJSON(c, &request) {
		return
	}
	reactions, err := h.getReactions(c.Request.Context(), agent, request.MessageID)
	if err != nil {
		c.JSON(HTTPStatus(err), agentError(err.Error()))
		return
	}
	c.JSON(http.StatusOK, dto.AgentReactionsResponse{Reactions: converter.ToMessageReactionAggregates(reactions)})
}

// Add records the authenticated agent's reaction and emits wake/realtime updates.
func (h *ReactionHandler) Add(c *gin.Context) {
	agent, ok := authenticate(c, h.auth)
	if !ok {
		return
	}
	var request dto.AgentReactionMutationRequest
	if !bindJSON(c, &request) {
		return
	}
	changed, reactions, err := h.addReaction(c.Request.Context(), agent, request.MessageID, request.Emoji)
	if err != nil {
		c.JSON(HTTPStatus(err), agentError(err.Error()))
		return
	}
	c.JSON(http.StatusOK, dto.AgentReactionMutationResponse{Changed: changed, Reactions: converter.ToMessageReactionAggregates(reactions)})
}

// Remove deletes the authenticated agent's reaction and emits realtime updates.
func (h *ReactionHandler) Remove(c *gin.Context) {
	agent, ok := authenticate(c, h.auth)
	if !ok {
		return
	}
	var request dto.AgentReactionMutationRequest
	if !bindJSON(c, &request) {
		return
	}
	changed, reactions, err := h.removeReaction(c.Request.Context(), agent, request.MessageID, request.Emoji)
	if err != nil {
		c.JSON(HTTPStatus(err), agentError(err.Error()))
		return
	}
	c.JSON(http.StatusOK, dto.AgentReactionMutationResponse{Changed: changed, Reactions: converter.ToMessageReactionAggregates(reactions)})
}
