package services

import (
	"fmt"
	"sync"

	"github.com/fiskerinc/cloud-services/pkg/grpc/sms"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	grpctrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/google.golang.org/grpc"
)

var smsClient sms.SMSServiceClient
var smsClientOnce sync.Once

func newSmsClient() {
	logger.Info().Msg("Init SMS client")
	target := fmt.Sprintf("%s:%s",
		envtool.GetEnv("SMS_HOST", "sms"),
		envtool.GetEnv("SMS_PORT", "8077"))
	// Create the client interceptor using the grpc trace package.
	si := grpctrace.StreamClientInterceptor(grpctrace.WithServiceName("sms-grpc-client"))
	ui := grpctrace.UnaryClientInterceptor(grpctrace.WithServiceName("sms-grpc-client"))
	c, err := grpc.Dial(target, grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithStreamInterceptor(si), grpc.WithUnaryInterceptor(ui))

	if err != nil {
		logger.Error().Err(err).Send()
	}

	smsClient = sms.NewSMSServiceClient(c)
}

func GetSMSClient() sms.SMSServiceClient {
	smsClientOnce.Do(func() {
		if smsClient != nil {
			return
		}
		newSmsClient()
	})

	return smsClient
}

func SetSmsClient(c sms.SMSServiceClient) {
	smsClient = c
}
