package agentkindboxreqservice

import (
	"context"

	paginationparam "git.gocasts.ir/ebhomengo/niki/param"
	param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box_req"
	response "git.gocasts.ir/ebhomengo/niki/pkg/response_builder"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

func (s Service) GetAllAwaitingDelivery(ctx context.Context, req param.DeliveryAwaitingGetAllRequest) (param.DeliveryAwaitingGetAllResponse, error) {
	const op = "agentkindboxreqservice.GetAllAwaitingDelivery"

	if fieldErrors, vErr := s.vld.ValidateGetAllAwaitingDelivery(req); vErr != nil {
		return param.DeliveryAwaitingGetAllResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr)
	}

	req.Pagination.GetPageSize()
	req.Pagination.GetPageNumber()
	req.Filter["sender_agent_id"] = req.SenderAgentId
	req.Filter["status"] = req.Status

	allAwaitingKindBoxReq, total, err := s.repo.GetAllKindBoxReq(ctx, req.Filter, req.Pagination, req.Sort, nil)
	if err != nil {
		return param.DeliveryAwaitingGetAllResponse{}, richerror.New(op).WithErr(err)
	}
	var data []param.Data
	for _, kindBoxReq := range allAwaitingKindBoxReq {
		data = append(data, param.Data{
			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:        response.GetNullDate(kindBoxReq.DeliveredAt),
		})
	}

	return param.DeliveryAwaitingGetAllResponse{
		Data: data,
		Pagination: paginationparam.PaginationResponse{
			PageSize:   req.Pagination.PageSize,
			PageNumber: req.Pagination.PageNumber,
			Total:      total,
		},
	}, nil
}
