package files

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/rose_cat707/luminary/internal/storage/imagestore"
)

type Handler struct {
	store *imagestore.Store
}

func New(store *imagestore.Store) *Handler {
	return &Handler{store: store}
}

func (h *Handler) Register(r *gin.Engine) {
	r.GET("/files/:id", h.Serve)
}

func (h *Handler) Serve(c *gin.Context) {
	id := c.Param("id")
	expStr := c.Query("exp")
	sig := c.Query("sig")
	exp, err := strconv.ParseInt(expStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid exp"})
		return
	}
	if !h.store.Verify(id, exp, sig) {
		c.JSON(http.StatusForbidden, gin.H{"error": "invalid signature"})
		return
	}
	img, err := h.store.Get(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
		return
	}
	c.Header("Content-Type", img.Mime)
	c.File(img.LocalPath)
}
