package service

import (
	"github.com/UpmeshLTD/urus-aio/cronjob/config"
	"github.com/UpmeshLTD/urus-aio/cronjob/external/shipment"
	logger "github.com/UpmeshLTD/urus-aio/cronjob/log"
	"github.com/UpmeshLTD/urus-aio/infrastructure/db/entities"
	"github.com/UpmeshLTD/urus-aio/shipment/server/grpc/pb"
	"github.com/avast/retry-go"
	"golang.org/x/net/context"
	"log"
	"time"
)

type Service interface {
	SyncCourierShipmentStatusKerryExpressTH()
}

type serviceImpl struct {
	config         config.Config
	logger         logger.Logger
	shipmentClient shipment.Service
}

func NewService(
	config config.Config,
	logger logger.Logger,
	shipmentClient shipment.Service,
) Service {
	return &serviceImpl{
		config:         config,
		logger:         logger,
		shipmentClient: shipmentClient,
	}
}

func (s *serviceImpl) SyncCourierShipmentStatusKerryExpressTH() {
	_ = retry.Do(func() error {
		res, err := s.shipmentClient.SyncCourierShipmentStatus(context.Background(), &pb.SyncCourierShipmentStatusRequest{
			Interval:  s.config.GetCronjobConfig().SyncCourierShipmentStatusInterval,
			CourierID: entities.CourierIdKerryExpressTH,
		})
		if err != nil {
			log.Println("SyncCourierShipmentStatusKerryExpressTH:", err)
			return err
		}
		log.Println("SyncCourierShipmentStatusKerryExpressTH:", res.Status)
		return nil
	}, retry.Attempts(3), retry.Delay(time.Second*10))
}
