package adminkindboxreqservice

import (
	"context"
	"time"

	kindboxParam "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box"
	param "git.gocasts.ir/ebhomengo/niki/param/admin/kind_box_req"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

func (s Service) Deliver(ctx context.Context, req param.DeliverKindBoxReqRequest) (param.DeliverKindBoxReqResponse, error) {
	const op = "adminkindboxreqservice.Deliver"

	kindBoxReq, gErr := s.repo.GetByID(ctx, req.KindBoxReqID)
	if gErr != nil {
		return param.DeliverKindBoxReqResponse{}, richerror.New(op).WithErr(gErr).WithKind(richerror.KindUnexpected)
	}
	_, aErr := s.kindBoxSvc.AddBatchKindBox(ctx, kindboxParam.AddKindBoxRequest{
		KindBoxReqID:     kindBoxReq.ID,
		BenefactorID:     kindBoxReq.BenefactorID,
		Type:             kindBoxReq.KindBoxType,
		DeliverReferDate: kindBoxReq.DeliverReferDate,
		DeliverAddressID: kindBoxReq.DeliverAddressID,
		SenderAgentID:    kindBoxReq.SenderAgentID,
		DeliveredAt:      time.Now(),
		CountAccepted:    kindBoxReq.CountAccepted,
	})
	if aErr != nil {
		return param.DeliverKindBoxReqResponse{}, richerror.New(op).WithErr(aErr).WithKind(richerror.KindUnexpected)
	}
	dErr := s.repo.DeliverKindBoxReq(ctx, req.KindBoxReqID)
	if dErr != nil {
		return param.DeliverKindBoxReqResponse{}, richerror.New(op).WithErr(dErr).WithKind(richerror.KindUnexpected)
	}

	return param.DeliverKindBoxReqResponse{}, nil
}
