package routes

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

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

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

	var Results []byte
	err := tools.Database.QueryRow(ctx,
		`SELECT COALESCE(jsonb_agg(t.row), '[]') FROM (
			SELECT jsonb_build_object(
				'id',     	 u.id::text,
				'created',	 u.created::timestamptz,
				'sticker',	 u.flag_sticker,
				'audio',	 u.flag_audio,
				'framerate', u.encode_fps,
				'width',  	 u.encode_width,
				'height', 	 u.encode_height,
				'rating',	 u.meta_rating,
				'title',  	 u.meta_title,
				'tags',    COALESCE(
					jsonb_agg(
						jsonb_build_object(
							'id',    t.id::text,
							'label', t.label,
							'usage', t.usage
						)
					) FILTER (WHERE t.id IS NOT NULL),
					'[]'
				)
			) AS row
			FROM gifuu.upload u
			LEFT JOIN gifuu.upload_tag ut ON ut.gif_id = u.id
			LEFT JOIN gifuu.tag t ON t.id = ut.tag_id
			WHERE ($1::bigint = 0 OR u.id < $1::bigint) AND u.meta_rating < $3
			GROUP BY u.id
			ORDER BY u.id DESC
			LIMIT $2
		) t`,
		paramAfter,
		paramLimit,
		tools.MODEL_THRESHOLD_HIDE,
	).Scan(&Results)
	if err != nil {
		tools.SendServerError(w, r, err)
		return
	}

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