package adminkindboxreqhandler

import (
	"net/http"

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

// GetAll godoc
// @Summary      Admin get all kindboxreq
// @Description  Retrieves a list of all KindBox requests with filtering, sorting, and pagination options
// @Tags         Admins KindBoxReqs
// @Accept       json
// @Produce      json
// @Param        search query string false "Search by id, phone_number, concat(first_name, last_name) benefactor"
// @Param        filter_id query int false "Filter by ID"
// @Param        filter_benefactor_id query int false "Filter by benefactor ID"
// @Param		 filter_sender_agent_id query int false "Filter by sender agent ID"
// @Param 		 filter_kind_box_type query entity.KindBoxType false "Filter by KindBox type" Format(enum)
// @Param 		 filter_status query entity.KindBoxReqStatus false "Filter by KindBoxReq status" Format(enum)
// @Param        filter_count_requested query int false "Filter by count requested"
// @Param        filter_count_accepted query int false "Filter by count accepted"
// @Param        filter_deliver_refer_time_id query int false "Filter by deliver refer time ID"
// @Param        filter_deliver_refer_date query string false "Filter by deliver refer date" Format(date)
// @Param        filter_deliver_address_id query int false "Filter by deliver address ID"
// @Param        filter_delivered_at query string false "Filter by delivered at" Format(date)
// @Param        page_number query int false "Page number"
// @Param        page_size query int false "Page size"
// @Param        sort_field query string false "Sort by field" Enums(id,benefactor_id,sender_agent_id,kind_box_type,status,count_requested,count_accepted,deliver_refer_time_id,deliver_refer_date,deliver_address_id,delivered_at)
// @Param        sort_direction query string false "Sort order" Enums(asc,desc)
// @Success      200  {array}  KindBoxReqsAggregatedResponse
// @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 [get].
func (h Handler) GetAll(c echo.Context) error {
	var req param.KindBoxReqGetAllRequest

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

	req.Filter = queryparam.GetFilterParams(c)

	kindBoxReqs, err := h.adminKindBoxReqSvc.GetAll(c.Request().Context(), req)
	if err != nil {
		msg, code := httpmsg.Error(err)
		if kindBoxReqs.FieldErrors != nil {
			return c.JSON(code, httpmsg.ErrorResponse{
				Message: msg,
				Errors:  kindBoxReqs.FieldErrors,
			})
		}

		return echo.NewHTTPError(code, msg)
	}

	benefactors, bErr := h.adminBenefactorAggSvc.GetByIDs(c.Request().Context(), getBenefactorIDs(kindBoxReqs.Data))
	if bErr != nil {
		msg, code := httpmsg.Error(bErr)

		return echo.NewHTTPError(code, msg)
	}
	var data []KindBoxReqAggregatedListResponse

	for _, kindBoxReq := range kindBoxReqs.Data {
		data = append(data, KindBoxReqAggregatedListResponse{
			ID:                 kindBoxReq.ID,
			BenefactorID:       kindBoxReq.BenefactorID,
			KindBoxType:        kindBoxReq.KindBoxType,
			CountRequested:     kindBoxReq.CountRequested,
			CountAccepted:      kindBoxReq.CountAccepted,
			Description:        kindBoxReq.Description,
			Status:             kindBoxReq.Status,
			DeliverReferTimeID: kindBoxReq.DeliverReferTimeID,
			DeliverReferDate:   kindBoxReq.DeliverReferDate,
			DeliverAddressID:   kindBoxReq.DeliverAddressID,
			SenderAgentID:      kindBoxReq.SenderAgentID,
			DeliveredAt:        kindBoxReq.DeliveredAt,
			Benefactor:         benefactors[kindBoxReq.BenefactorID],
		})
	}
	resp := KindBoxReqsAggregatedResponse{
		Data:       data,
		Pagination: kindBoxReqs.Pagination,
	}
	return c.JSON(http.StatusOK, resp)
}

func getBenefactorIDs(kindBoxReqs []param.Data) []any {
	benefactorsMap := make(map[uint]bool)
	for _, kindBox := range kindBoxReqs {
		benefactorsMap[kindBox.BenefactorID] = true
	}
	return arrayfunc.MapToSlice(benefactorsMap)
}
