package shipment

import (
	"context"
	"github.com/UpmeshLTD/urus-aio/cronjob/config"
	logger "github.com/UpmeshLTD/urus-aio/cronjob/log"
	"github.com/UpmeshLTD/urus-aio/shipment/server/grpc/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type Service interface {
	Ping(ctx context.Context, req *pb.PingRequest) (*pb.PingResponse, error)
	SyncCourierShipmentStatus(ctx context.Context, req *pb.SyncCourierShipmentStatusRequest) (*pb.SyncCourierShipmentStatusResponse, error)
}

type serviceImpl struct {
	conn   *grpc.ClientConn
	client pb.ShipmentServiceClient
	logger logger.Logger
}

func NewService(cfg config.Config, logger logger.Logger) (Service, error) {
	address := cfg.GetGRPCConfig().ShipmentAddress
	conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		logger.Errorw("initializing Shipment GRPC client failed", "address", address, "error", err)
		return nil, err
	}

	client := pb.NewShipmentServiceClient(conn)
	return &serviceImpl{
		conn:   conn,
		client: client,
		logger: logger,
	}, nil
}

func (s *serviceImpl) Ping(ctx context.Context, req *pb.PingRequest) (*pb.PingResponse, error) {
	return s.client.Ping(ctx, req)
}

func (s *serviceImpl) SyncCourierShipmentStatus(ctx context.Context, req *pb.SyncCourierShipmentStatusRequest) (*pb.SyncCourierShipmentStatusResponse, error) {
	return s.client.SyncCourierShipmentStatus(ctx, req)
}
