package agentkindboxreqhandler

import (
	"context"
	"net/http"

	params "git.gocasts.ir/ebhomengo/niki/param"
	param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box_req"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
	querier "git.gocasts.ir/ebhomengo/niki/pkg/query_transaction/sql"
	echo "github.com/labstack/echo/v4"
)

// Deliver godoc
// @Summary      Agent deliver a kindboxreq
// @Tags         Agents KindBoxReqs
// @Accept       json
// @Produce      json
// @Param 		 id path int true "KindBoxReq ID"
// @Param        Request body   param.DeliverKindBoxReqRequest true "KindBoxReq deliver request details"
// @Success      200  {object}   param.DeliverKindBoxReqResponse
// @Failure      400  {string}  "Bad request"
// @Security 	 AuthBearerAdmin
// @Router       /agents/kindboxreqs/{id}/deliver-kind-box-req [patch].
func (h Handler) Deliver(c echo.Context) error {
	var req param.DeliverKindBoxReqRequest

	if bErr := c.Bind(&req); bErr != nil {
		return echo.NewHTTPError(http.StatusBadRequest)
	}

	q := querier.GetQuerierFromContextOrNew(c.Request().Context()).Begin()
	ctx := context.WithValue(c.Request().Context(), querier.QuerierContextKey, q)
	resp, sErr := h.agentKindBoxReqSvc.Deliver(ctx, req)
	if sErr != nil {
		msg, code := httpmsg.Error(sErr)
		if resp.FieldErrors != nil {
			return c.JSON(code, echo.Map{
				"message": msg,
				"errors":  resp.FieldErrors,
			})
		}
		rErr := q.Rollback()
		if rErr != nil {
			return echo.NewHTTPError(http.StatusInternalServerError, errmsg.ErrorMsgSomethingWentWrong)
		}

		return echo.NewHTTPError(code, msg)
	}
	cErr := q.Commit()
	if cErr != nil {
		return echo.NewHTTPError(http.StatusInternalServerError, errmsg.ErrorMsgSomethingWentWrong)
	}

	go h.notificationSvc.KindBoxReqDelivered(params.NotificationKindBoxReqDelivered{
		KindBoxReqID: req.KindBoxReqID,
	})

	return c.JSON(http.StatusOK, resp)
}
