package agentkindboxreqservice

import (
	"context"
	"time"

	kindboxParam "git.gocasts.ir/ebhomengo/niki/param/agent/kind_box"
	param "git.gocasts.ir/ebhomengo/niki/param/agent/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 = "agentkindboxreqservice.Deliver"
	if fieldErrors, vErr := s.vld.ValidateDeliver(ctx, req); vErr != nil {
		return param.DeliverKindBoxReqResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr)
	}

	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,
		DeliverReferTimeID: kindBoxReq.DeliverReferTimeID,
		DeliverReferDate:   kindBoxReq.DeliverReferDate,
		DeliverAddressID:   kindBoxReq.DeliverAddressID,
		SenderAgentID:      kindBoxReq.SenderAgentID,
		DeliveredAt:        time.Now(),
		CountAccepted:      kindBoxReq.CountAccepted,
		SerialNumbers:      req.SerialNumbers,
	})
	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
}
