package routes

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

	"github.com/jackc/pgx/v5"
)

func GET_Art_ID(w http.ResponseWriter, r *http.Request) {

	paramID := tools.ParseSnowflake(r.PathValue("id"))
	if paramID == 0 {
		tools.SendClientError(w, r, tools.ERROR_BODY_INVALID_FIELD)
		return
	}

	var Results []byte
	err := tools.Database.QueryRow(r.Context(),
		`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(
					CASE WHEN t.id IS NOT NULL THEN
						jsonb_build_object(
							'id',    t.id::text,
							'label', t.label,
							'usage', t.usage
						)
					END
				) FILTER (WHERE t.id IS NOT NULL),
				'[]'
			)
		)
		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 u.id = $1
		GROUP BY u.id`,
		paramID,
	).Scan(&Results)

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

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