package handlers

import (
	"net/http"

	"veza-backend-api/internal/services"

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

var SearchHandlersInstance *SearchHandlers

// SearchServiceInterface defines the interface for search operations
// This allows for easier testing with mocks
type SearchServiceInterface interface {
	Search(query string, types []string) (*services.SearchResult, error)
}

type SearchHandlers struct {
	searchService SearchServiceInterface
}

func NewSearchHandlers(searchService *services.SearchService) {
	SearchHandlersInstance = &SearchHandlers{
		searchService: searchService,
	}
}

// NewSearchHandlersWithInterface creates new search handlers with an interface (for testing)
func NewSearchHandlersWithInterface(searchService SearchServiceInterface) *SearchHandlers {
	return &SearchHandlers{
		searchService: searchService,
	}
}

// Search performs a full-text search across tracks, users, and playlists
func (sh *SearchHandlers) Search(c *gin.Context) {
	query := c.Query("q")
	if query == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Search query is required"})
		return
	}

	types := c.QueryArray("type")

	results, err := sh.searchService.Search(query, types)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	RespondSuccess(c, http.StatusOK, results)
}
