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 makeDeleteHandler(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)
		}()

		req := c.Request
		if err := req.ParseForm(); err != nil {
			log.Printf("Failed to parse deletion confirm form for queue %s: %v",
				qName, err)
			sess.AddFlash(fmt.Sprintf("Failed to parsed deletion confirmm form for queue %s",
				qName))
			return
		}
		ids := parseIDs(req.Form, validateUint)

		var messages []redriver.Message
		if len(ids) == 0 {
			flash := fmt.Sprintf("Got no message to delete from queue %q", qName)
			log.Print(flash)
			sess.AddFlash(flash)
			return
		}
		messages = parseMessages(req.Form, ids)

		keys := make([]redriver.ItemsKeys, len(messages))
		for i, msg := range messages {
			keys[i] = msg.Keys()
		}
		t0 := time.Now()
		err := rd.DeleteItems(ctx, qName, keys)
		latency := time.Since(t0)
		if err != nil {
			log.Printf("failed deleting %d items from queue %q: %v",
				len(keys), qName, err)
			sess.AddFlash(fmt.Sprintf("Failed deleting %d items from queue %q",
				len(keys), qName))
			return
		}

		sess.AddFlash(fmt.Sprintf("Deleted %d items from queue %s in %v", len(keys),
			qName, latency))
	}
}
