package adminkindboxreqhandler

import (
	"net/http"

	param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
	httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
	"github.com/labstack/echo/v4"
)

// Get godoc
// @Summary      Get a specific kind box req by ID
// @Tags         Admins KindBoxReqs
// @Accept       json
// @Produce      json
// @Param        id path int true "KindBoxReq ID"
// @Success      200  {object}  KindBoxReqAggregatedResponse
// @Failure      400  {string}  "Bad Request"
// @Failure      401  {string}  "invalid or expired jwt"
// @Failure      403  {string}  "user not allowed"
// @Failure      422  {object}  httpmsg.ErrorResponse
// @Failure      500  {string}  "something went wrong"
// @Security 	 AuthBearerAdmin
// @Router       /admins/kindboxreqs/{id} [get].
func (h Handler) Get(c echo.Context) error {
	var req param.GetKindBoxReqRequest
	if err := c.Bind(&req); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest)
	}

	kindBoxReq, err := h.adminKindBoxReqSvc.Get(c.Request().Context(), req)
	if err != nil {
		msg, code := httpmsg.Error(err)
		if kindBoxReq.FieldErrors != nil {
			return c.JSON(code, echo.Map{
				"message": msg,
				"errors":  kindBoxReq.FieldErrors,
			})
		}

		return echo.NewHTTPError(code, msg)
	}

	benefactor, bErr := h.adminBenefactorAggSvc.GetByID(c.Request().Context(), kindBoxReq.Data.BenefactorID)
	if bErr != nil {
		msg, code := httpmsg.Error(bErr)

		return echo.NewHTTPError(code, msg)
	}

	deliverAddress, dAErr := h.addressAggSvc.GetAggregatedByID(c.Request().Context(), kindBoxReq.Data.DeliverAddressID)
	if dAErr != nil {
		msg, code := httpmsg.Error(dAErr)

		return echo.NewHTTPError(code, msg)
	}

	deliverReferTime, dRErr := h.referTimeAggSvc.GetReferTimeByID(c.Request().Context(), kindBoxReq.Data.DeliverReferTimeID)
	if dRErr != nil {
		msg, code := httpmsg.Error(dRErr)

		return echo.NewHTTPError(code, msg)
	}

	resp := KindBoxReqAggregatedResponse{
		ID:                 kindBoxReq.Data.ID,
		BenefactorID:       kindBoxReq.Data.BenefactorID,
		KindBoxType:        kindBoxReq.Data.KindBoxType,
		CountRequested:     kindBoxReq.Data.CountRequested,
		CountAccepted:      kindBoxReq.Data.CountAccepted,
		Description:        kindBoxReq.Data.Description,
		Status:             kindBoxReq.Data.Status,
		DeliverReferTimeID: kindBoxReq.Data.DeliverReferTimeID,
		DeliverReferDate:   kindBoxReq.Data.DeliverReferDate,
		DeliverAddressID:   kindBoxReq.Data.DeliverAddressID,
		SenderAgentID:      kindBoxReq.Data.SenderAgentID,
		DeliveredAt:        kindBoxReq.Data.DeliveredAt,
		Benefactor:         benefactor,
		DeliverAddress:     deliverAddress,
		DeliverReferTime:   deliverReferTime,
	}
	return c.JSON(http.StatusOK, resp)
}
