package session

import (
	"net/http"

	"github.com/gin-gonic/gin"

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

// SessionsHandler handles requests to list interactive sessions.
type SessionsHandler struct {
	store SessionsStore
}

// RestartHandler handles requests to refresh a running interactive session.
type RestartHandler struct {
	store SessionRestartStore
}

// NewSessionsHandler creates a new SessionsHandler.
func NewSessionsHandler(store SessionsStore) gin.HandlerFunc {
	return (&SessionsHandler{store: store}).Handle
}

// NewRestartHandler creates a new RestartHandler.
func NewRestartHandler(store SessionRestartStore) gin.HandlerFunc {
	return (&RestartHandler{store: store}).Handle
}

// Handle returns active sessions.
func (h *SessionsHandler) Handle(c *gin.Context) {
	resp := dto.SessionsResponse{}

	if h.store != nil {
		resp.Active = dto.SessionSnapshotResponsesFromTypes(h.store.Sessions())
	}

	c.JSON(http.StatusOK, resp)
}

// Handle retires a running leader runtime so the next wake uses fresh settings.
func (h *RestartHandler) Handle(c *gin.Context) {
	agentID := c.Param("agentId")
	if h.store == nil || !h.store.RestartByAgent(agentID) {
		c.JSON(http.StatusNotFound, gin.H{"error": "no active session for agent"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"restarted": true})
}
