package adminkindboxhandler

import (
	"net/http"

	param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
	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"
	"github.com/labstack/echo/v4"
)

// GetAll godoc
// @Summary 	 Get all KindBoxes by admin
// @Description  Retrieves a list of all KindBoxes with filtering, sorting, and pagination options
// @Tags         Admins KindBoxes
// @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_kind_box_req_id query int false "Filter by KindBox request ID"
// @Param        filter_benefactor_id query int false "Filter by benefactor ID"
// @Param 		 filter_type query string false "Filter by KindBox type" Enums(on-table,cylindrical,stand-up)
// @Param        filter_amount query int false "Filter by amount"
// @Param        filter_serial_number query string false "Filter by serial number"
// @Param        filter_status query string false "Filter by status" Enums(delivered,ready-to-return,assigned-receiver-agent,returned,enumerated)
// @Param        filter_delivered_at query string false "Filter by delivered at" Format(date-time)
// @Param        filter_return_refer_time_id query int false "Filter by return refer time ID"
// @Param        filter_return_refer_date query string false "Filter by return refer date" Format(date)
// @Param        filter_return_address_id query int false "Filter by return address ID"
// @Param        filter_receiver_agent_id query int false "Filter by receiver agent ID"
// @Param        filter_returned_at query string false "Filter by returned at" Format(date-time)
// @Param        filter_sender_agent_id query int false "Filter by sender agent 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_deliver_refer_time_id query int false "Filter by deliver refer time ID"
// @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,kind_box_req_id,benefactor_id,kind_box_type,amount,serial_number,status,delivered_at,return_refer_time_id,return_refer_date,return_address_id,receiver_agent_id,returned_at,sender_agent_id,deliver_refer_date,deliver_address_id,deliver_refer_time_id)
// @Param        sort_direction query string false "Sort order" Enums(asc,desc)
// @Success      200  {array}  KindBoxesAggregatedResponse
// @Failure      400  {string}  "Bad request"
// @Security 	 AuthBearerAdmin
// @Router       /admins/kindboxes [get].
func (h Handler) GetAll(c echo.Context) error {
	var req param.KindBoxGetAllRequest

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

	req.Filter = queryparam.GetFilterParams(c)

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

		return echo.NewHTTPError(code, msg)
	}

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

		return echo.NewHTTPError(code, msg)
	}

	deliverReferTime, dRErr := h.referTimeAggSvc.GetReferTimeByIDs(c.Request().Context(), getDeliverReferTimeIDs(kindBoxes.Data))
	if dRErr != nil {
		msg, code := httpmsg.Error(dRErr)

		return echo.NewHTTPError(code, msg)
	}

	returnReferTime, rRErr := h.referTimeAggSvc.GetReferTimeByIDs(c.Request().Context(), getReturnReferTimeIDs(kindBoxes.Data))
	if rRErr != nil {
		msg, code := httpmsg.Error(rRErr)

		return echo.NewHTTPError(code, msg)
	}

	var data []KindBoxAggregatedListResponse

	for _, kindBox := range kindBoxes.Data {
		data = append(data, KindBoxAggregatedListResponse{
			ID:                 kindBox.ID,
			KindBoxReqID:       kindBox.KindBoxReqID,
			BenefactorID:       kindBox.BenefactorID,
			KindBoxType:        kindBox.KindBoxType,
			Amount:             kindBox.Amount,
			SerialNumber:       kindBox.SerialNumber,
			Status:             kindBox.Status,
			DeliverReferTimeID: kindBox.DeliverReferTimeID,
			DeliverReferDate:   kindBox.DeliverReferDate,
			DeliverAddressID:   kindBox.DeliverAddressID,
			SenderAgentID:      kindBox.SenderAgentID,
			DeliveredAt:        kindBox.DeliveredAt,
			ReturnReferTimeID:  kindBox.ReturnReferTimeID,
			ReturnReferDate:    kindBox.ReturnReferDate,
			ReturnAddressID:    kindBox.ReturnAddressID,
			ReceiverAgentID:    kindBox.ReceiverAgentID,
			ReturnedAt:         kindBox.ReturnedAt,
			Benefactor:         benefactors[kindBox.BenefactorID],
			DeliverReferTime:   deliverReferTime[kindBox.DeliverReferTimeID],
			ReturnReferTime:    returnReferTime[kindBox.ReturnReferTimeID],
		})
	}

	resp := KindBoxesAggregatedResponse{
		Data:       data,
		Pagination: kindBoxes.Pagination,
	}
	return c.JSON(http.StatusOK, resp)
}

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

func getDeliverReferTimeIDs(kindBoxes []param.Data) []any {
	deliverReferTimesMap := make(map[uint]bool)
	for _, kindBox := range kindBoxes {
		deliverReferTimesMap[kindBox.DeliverReferTimeID] = true
	}
	return arrayfunc.MapToSlice(deliverReferTimesMap)
}

func getReturnReferTimeIDs(kindBoxes []param.Data) []any {
	returnReferTimesMap := make(map[uint]bool)
	for _, kindBox := range kindBoxes {
		returnReferTimesMap[kindBox.ReturnReferTimeID] = true
	}
	return arrayfunc.MapToSlice(returnReferTimesMap)
}
