package routes

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

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

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

	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 usage DESC
			LIMIT $1
		) t`,
		paramLimit,
	).Scan(&Results)

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

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