package web

import (
	"log"
	"net/http"
	"time"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"

	"code.osinet.fr/fgm/sqs_demo/back/services/redriver"
)

func makeQueueHandler(rd redriver.Redriver, ms redriver.MessageStore) gin.HandlerFunc {
	return func(c *gin.Context) {
		ctx := c.Request.Context()
		qName := c.Param("name")

		sess := sessions.Default(c)
		flashes := sess.Flashes()
		_ = sess.Save()

		t0 := time.Now()
		qi, err := rd.GetQueueInfo(ctx, qName)
		infoLatency := time.Since(t0)
		if err != nil {
			log.Printf("failed getting info for queue %q: %v", qName, err)
			c.HTML(http.StatusInternalServerError, "500", nil)
			return
		}
		items, err := rd.GetQueueItems(ctx, qName)
		if err != nil {
			log.Printf("failed getting items for queue %q: %v", qName, err)
			c.HTML(http.StatusInternalServerError, "500", nil)
			return
		}
		for _, item := range items {
			ms.Set(item)
		}
		itemsLatency := time.Since(t0) - infoLatency
		c.HTML(http.StatusOK, "queue-get", gin.H{
			"flashes": flashes,
			"info":    qi,
			"isDLQ":   qi.IsDLQ(),
			"items":   items,
			"latency": map[string]time.Duration{
				"info":  infoLatency,
				"items": itemsLatency,
			},
		})
	}
}
