package benefactorkindboxreqservice

import (
	"context"

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

func (s Service) GetAll(ctx context.Context, req param.GetAllRequest) (param.GetAllResponse, error) {
	const op = "benefactorkindboxreqservice.GetAll"
	if fieldErrors, vErr := s.vld.ValidateGetAll(req); vErr != nil {
		return param.GetAllResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr)
	}

	req.Filter["benefactor_id"] = req.BenefactorId
	req.Pagination.GetPageSize()
	req.Pagination.GetPageNumber()

	allKindBoxReq, total, err := s.repo.GetAllKindBoxReq(ctx, req.Filter, req.Pagination, req.Sort, nil)
	if err != nil {
		return param.GetAllResponse{}, richerror.New(op).WithErr(err)
	}

	var data []param.Data
	for _, kindBoxReq := range allKindBoxReq {
		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.GetAllResponse{
		Data: data,
		Pagination: params.PaginationResponse{
			PageSize:   req.Pagination.PageSize,
			PageNumber: req.Pagination.PageNumber,
			Total:      total,
		},
	}, nil
}
