package api

import (
	"errors"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/alertstore/pkg/directory"
)

// userSuggestionLimit is how many people one keystroke's worth of typing may
// offer. A picker nobody scrolls is a picker that answers in one glance; past
// about this many rows, typing another character is faster than reading on.
const userSuggestionLimit = 8

// searchUsers backs the assignee autocomplete in the web UI. It proxies
// core-server's directory rather than letting the browser call it, so the
// gateway credential stays server-side and the UI keeps talking to one origin.
//
// An unconfigured or unreachable directory returns an empty list, not an error:
// the field it feeds is free text, and an operator who already knows the
// address should not be stopped by a search that cannot answer.
//
//	@Summary	Search the user directory for the assignee picker
//	@Id			searchUsers
//	@Tags		Users
//	@Produce	json
//	@Param		q	query		string			false	"Name or email fragment"
//	@Success	200	{object}	UsersResponse	"Empty when the directory is disabled or unreachable"
//	@Router		/bff/users [get]
func (s *Server) searchUsers(c *gin.Context) {
	keyword := strings.TrimSpace(c.Query("q"))
	if keyword == "" {
		c.JSON(http.StatusOK, UsersResponse{Users: []directory.User{}})
		return
	}

	users, err := s.directory.Search(c.Request.Context(), keyword, userSuggestionLimit)
	if err != nil {
		if !errors.Is(err, directory.ErrDisabled) {
			s.logger.Warn("search user directory", "err", err, "keyword", keyword)
		}
		c.JSON(http.StatusOK, UsersResponse{Users: []directory.User{}})
		return
	}
	c.JSON(http.StatusOK, UsersResponse{Users: users})
}
