package restimage

import (
	"io"
	"log/slog"
	"net/http"

	"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
	"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
)

func (h *Handler) getImage(w http.ResponseWriter, r *http.Request) {
	uid := r.PathValue("uid")

	var err error
	options := images.Options{}
	options.Height, err = rest.IntParam(r, "h")
	if err != nil {
		rest.SendErr(w, err)
		return
	}
	options.Width, err = rest.IntParam(r, "w")
	if err != nil {
		rest.SendErr(w, err)
		return
	}

	options.Quality, err = rest.IntParam(r, "q")
	if err != nil {
		rest.SendErr(w, err)
		return
	}

	img, mime, err := h.img.GetScaledImage(r.Context(), uid, options)
	if err != nil {
		slog.Error("error wile serving image", "err", err, "uid", uid)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Header().Add("Content-Type", mime)
	io.Copy(w, img)
}
