package routes

import (
	"gifuu/tools"
	"net/http"
)

func GET_Tags_Autocomplete(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	query := r.URL.Query()

	paramLimit := tools.ParseLimit(query.Get("limit"))
	paramQuery := query.Get("query")

	if str, ok := tools.NormalizeTag(paramQuery); !ok {
		tools.SendClientError(w, r, tools.ERROR_BODY_INVALID_FIELD)
		return
	} else {
		paramQuery = str
	}

	var Results []byte
	err := tools.Database.QueryRow(ctx,
		`SELECT COALESCE(jsonb_agg(t), '[]') FROM (
			SELECT id::text AS id, label, usage
			FROM gifuu.tag
			ORDER BY word_similarity(label, $1) DESC, usage DESC
			LIMIT $2
		) t`,
		paramQuery,
		paramLimit,
	).Scan(&Results)

	if err != nil {
		tools.SendServerError(w, r, err)
		return
	}

	tools.SendJSON(w, r, http.StatusOK, Results)
}
