package agentkindboxservice

import (
	"context"

	paginationparam "git.gocasts.ir/ebhomengo/niki/param"
	param "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box"
	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 = "agentkindboxservice.GetAll"
	if fieldErrors, vErr := s.vld.ValidateGetAll(req); vErr != nil {
		return param.GetAllResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr)
	}

	req.Pagination.GetPageSize()
	req.Pagination.GetPageNumber()

	req.Filter["receiver_agent_id"] = req.ReceiverAgentId
	req.Filter["status"] = req.Status

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

	var data []param.Data
	for _, kindBox := range allKindBoxes {
		data = append(data, param.Data{
			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:    response.GetNullDate(kindBox.ReturnReferDate),
			ReturnAddressID:    kindBox.ReturnAddressID,
			ReceiverAgentID:    kindBox.ReceiverAgentID,
			ReturnedAt:         response.GetNullDate(kindBox.ReturnedAt),
		})
	}

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