package rest

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/nexuscrm/backend/internal/features/mru"
)

// SearchScopeHandler handles /search/scopeOrder endpoint
type SearchScopeHandler struct {
	mruService *mru.Service
}

// NewSearchScopeHandler creates a new SearchScopeHandler
func NewSearchScopeHandler(mruService *mru.Service) *SearchScopeHandler {
	return &SearchScopeHandler{mruService: mruService}
}

// GetScopeOrder handles GET /services/data/vXX.X/search/scopeOrder
// Returns the default global search scope for the logged-in user
// Salesforce-compatible response format
//
// @Summary      Get Search Scope and Order
// @Description  Returns the default global search scope and order for the logged-in user
// @Tags         search
// @Produce      json
// @Success      200  {array}  mru.ScopeOrderItem
// @Failure      401  {object}  map[string]interface{}
// @Router       /search/scopeOrder [get]
// @Security     BearerAuth
func (h *SearchScopeHandler) GetScopeOrder(c *gin.Context) {
	user := MustGetUser(c)

	// Extract API version from path (e.g., /services/data/v63.0/search/scopeOrder)
	apiVersion := extractAPIVersion(c.Request.URL.Path)

	result := h.mruService.GetScopeOrder(c.Request.Context(), user.ID, apiVersion)
	c.JSON(http.StatusOK, result)
}

// extractAPIVersion extracts the API version from the request path
func extractAPIVersion(path string) string {
	// Look for pattern like "v63.0" in the path
	parts := strings.Split(path, "/")
	for _, part := range parts {
		if strings.HasPrefix(part, "v") && strings.Contains(part, ".") {
			return part
		}
	}
	return "v63.0" // Default version
}
