package adminkindboxservice

import (
	"context"

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

func (s Service) Update(ctx context.Context, req param.KindBoxUpdateRequest) (param.KindBoxUpdateResponse, error) {
	const op = "adminkindboxservice.Update"

	// Validate the request using a validation service
	if fieldErrors, vErr := s.vld.ValidateUpdateRequest(ctx, req); vErr != nil {
		return param.KindBoxUpdateResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr)
	}

	// Fetch the current kind box data from the repository
	kindBox, err := s.repo.GetKindBox(ctx, req.KindBoxID)
	if err != nil {
		return param.KindBoxUpdateResponse{}, richerror.New(op).WithErr(err)
	}

	// Update the fields that are non-zero or non-default values
	if req.Amount != 0 {
		kindBox.Amount = req.Amount
	}
	if req.ReturnReferTimeID != 0 {
		kindBox.ReturnReferTimeID = req.ReturnReferTimeID
	}
	if !req.ReturnReferDate.IsZero() {
		kindBox.ReturnReferDate = req.ReturnReferDate
	}
	if req.ReturnAddressID != 0 {
		kindBox.ReturnAddressID = req.ReturnAddressID
	}
	if req.ReceiverAgentID != 0 {
		kindBox.ReceiverAgentID = req.ReceiverAgentID
	}

	// Update the kind box in the repository
	if uErr := s.repo.UpdateKindBox(ctx, kindBox); uErr != nil {
		return param.KindBoxUpdateResponse{}, richerror.New(op).WithErr(uErr)
	}

	// Return a successful response
	return param.KindBoxUpdateResponse{}, nil
}
