package services

import (
	"github.com/fiskerinc/cloud-services/pkg/grpc/sms"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"sync"
)

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"))
	c, err := grpc.Dial(target, grpc.WithTransportCredentials(insecure.NewCredentials()))
	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
}
