package benefactorkindboxhandler

import (
	"net/http"

	params "git.gocasts.ir/ebhomengo/niki/param"
	param "git.gocasts.ir/ebhomengo/niki/param/benefactor/kind_box"
	"git.gocasts.ir/ebhomengo/niki/pkg/claim"
	httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
	"github.com/labstack/echo/v4"
)

// RegisterEmptyingRequest godoc
// @Summary      Register a new emptying request for a kind box by benefactor
// @Tags         Benefactors KindBoxes
// @Accept       json
// @Produce      json
// @Param        id path int true "KindBox ID"
// @Param        Request body   param.KindBoxRegisterEmptyingRequest  true  "Request body"
// @Success      204  {string}  "No content"
// @Failure      400  {string}  "Bad request"
// @Security     AuthBearerBenefactor
// @Router       /benefactors/kindboxes/{id}/emptying-requests [patch].
func (h Handler) RegisterEmptyingRequest(c echo.Context) error {
	var req param.KindBoxRegisterEmptyingRequest
	if bErr := c.Bind(&req); bErr != nil {
		return echo.NewHTTPError(http.StatusBadRequest)
	}

	claims := claim.GetClaimsFromEchoContext(c)
	req.BenefactorID = claims.UserID

	resp, sErr := h.benefactorKindBoxSvc.RegisterEmptyingRequest(c.Request().Context(), req)
	if sErr != nil {
		msg, code := httpmsg.Error(sErr)
		if resp.FieldErrors != nil {
			return c.JSON(code, echo.Map{
				"message": msg,
				"errors":  resp.FieldErrors,
			})
		}

		return echo.NewHTTPError(code, msg)
	}

	go h.notificationSvc.KindBoxRegisteredEmptyingRequest(params.NotificationKindBoxRegisteredEmptyingRequest{
		KindBoxID: resp.Data.ID,
	})

	return c.JSON(http.StatusNoContent, nil)
}
