package search

import (
	"log"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"senlinai-agent/backend/internal/httpx"
	"senlinai-agent/backend/internal/logic/auth"
)

// Handler 将关键词搜索服务注册为受认证的 HTTP 接口。
type Handler struct {
	service *Service
}

// SearchResponseDTO 统一包装关键词搜索结果，空结果保持为空数组而不是 null。
type SearchResponseDTO struct {
	Items []SearchResultDTO `json:"items"`
}

// NewHandler 创建搜索 HTTP registrar。
func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

// Register 将搜索接口注册到上层提供的 /api/v1 路由组。
func (h *Handler) Register(router gin.IRouter) {
	router.GET("/search", h.search)
}

func (h *Handler) search(c *gin.Context) {
	userID, ok := auth.CurrentUserID(c)
	if !ok {
		httpx.Error(c, http.StatusUnauthorized, "unauthorized", "未登录或登录已失效")
		return
	}
	query := strings.TrimSpace(c.Query("q"))
	if query == "" {
		httpx.Error(c, http.StatusBadRequest, "invalid_query", "请输入搜索关键词")
		return
	}
	items, err := h.service.Search(userID, query)
	if err != nil {
		log.Printf("search failed for user %d: %v", userID, err)
		httpx.Error(c, http.StatusInternalServerError, "internal_error", "搜索失败，请稍后重试")
		return
	}
	if items == nil {
		items = []SearchResultDTO{}
	}
	c.JSON(http.StatusOK, SearchResponseDTO{Items: items})
}
