package web

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

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

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

func makePurgeHandler(rd redriver.Redriver) gin.HandlerFunc {
	return func(c *gin.Context) {
		ctx := c.Request.Context()
		qName := c.Param("name")
		redirect := "/queue/" + qName

		sess := sessions.Default(c)
		// Do not consume sess.Flashes(): this is a redirect-only handler, and they would be lost.
		defer func() {
			_ = sess.Save()
			c.Redirect(http.StatusSeeOther, redirect)
		}()

		t0 := time.Now()
		err := rd.Purge(ctx, qName)
		latency := time.Since(t0)
		if err != nil {
			log.Printf("failed purging queue %q: %v", qName, err)
			sess.AddFlash(fmt.Sprintf("Failed purging queue %q", qName))
			return
		}

		sess.AddFlash(fmt.Sprintf("Purged submitted for queue %s in %v", qName,
			latency))
		sess.AddFlash("The actual purge process takes up to 60 seconds, " +
			"so not be surprised if some messages are still visible on the queue messsages list." +
			"We recommend waiting for 60 seconds to refresh, regardless of your queue's size.")
	}
}
