package routes

import (
	"fmt"
	"gifuu/include"
	"gifuu/tools"
	"html"
	"log"
	"net/http"
	"strings"
	"text/template"

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

var animTemplate = template.Must(template.New("").Parse(include.TEMPLATE_ANIMATION_METADATA))

func GET_Metadata_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 animationData struct {
		Created string
		Width   int
		Height  int
		Rating  float64
		Sticker bool
		Title   string
		Tags    []string
	}

	// Fetch Animation Metadata
	err := tools.Database.QueryRow(r.Context(),
		`SELECT
			u.encode_width,
			u.encode_height,
			u.meta_rating,
			u.flag_sticker,
			u.meta_title,
			COALESCE(array_agg(t.label ORDER BY t.usage) 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(
		&animationData.Width,
		&animationData.Height,
		&animationData.Rating,
		&animationData.Sticker,
		&animationData.Title,
		&animationData.Tags,
	)
	if err == pgx.ErrNoRows {
		tools.SendClientError(w, r, tools.ERROR_UNKNOWN_ANIMATION)
		return
	}
	if err != nil {
		tools.SendServerError(w, r, err)
		return
	}

	// Render Webpage
	w.Header().Add("Content-Type", "text/html")
	err = animTemplate.Execute(w, map[string]any{
		"width":     animationData.Width,
		"height":    animationData.Height,
		"title":     html.EscapeString(animationData.Title),
		"tags":      html.EscapeString(strings.Join(animationData.Tags, ", ")),
		"uri_embed": fmt.Sprintf("%s/embed.html?id=%d&quality=standard", tools.TEMPLATE_BASE_WEB, paramID),
		"uri_image": fmt.Sprintf("%s/%d/standard.avif", tools.TEMPLATE_BASE_CDN, paramID),
		"uri_site":  fmt.Sprintf("%s/art/%d", tools.TEMPLATE_BASE_WEB, paramID),
	})
	if err != nil {
		log.Println("Render Error:", r.URL.Path, err)
		http.Error(w, "Server Error", http.StatusInternalServerError)
		return
	}
}
