package session

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
)

// MemorySearchMaintenanceStore exposes user-initiated derivative maintenance.
// Clear removes only the derived index; Rebuild keeps the current generation
// serving while a side-by-side replacement is built.
type MemorySearchMaintenanceStore interface {
	ClearMemorySearch(ctx context.Context, agentID string) error
	RebuildMemorySearch(ctx context.Context, agentID string) error
}

func NewClearMemorySearchHandler(store MemorySearchMaintenanceStore) gin.HandlerFunc {
	return func(c *gin.Context) {
		agentID, ok := agentIDParam(c)
		if !ok {
			return
		}
		if store == nil {
			c.JSON(http.StatusServiceUnavailable, gin.H{"error": "memory search maintenance unavailable"})
			return
		}
		if err := store.ClearMemorySearch(c.Request.Context(), agentID); err != nil {
			c.JSON(http.StatusConflict, gin.H{"error": "memory search clear failed"})
			return
		}
		c.JSON(http.StatusOK, gin.H{"cleared": true})
	}
}

func NewRebuildMemorySearchHandler(store MemorySearchMaintenanceStore) gin.HandlerFunc {
	return func(c *gin.Context) {
		agentID, ok := agentIDParam(c)
		if !ok {
			return
		}
		if store == nil {
			c.JSON(http.StatusServiceUnavailable, gin.H{"error": "memory search maintenance unavailable"})
			return
		}
		if err := store.RebuildMemorySearch(c.Request.Context(), agentID); err != nil {
			c.JSON(http.StatusConflict, gin.H{"error": "memory search rebuild failed"})
			return
		}
		c.JSON(http.StatusAccepted, gin.H{"rebuildQueued": true})
	}
}
