package resolver

import (
	"google.golang.org/grpc"
	"sync"
)

var (
	mu   = sync.RWMutex{}
	conn = make(map[string]*grpc.ClientConn)
)

func GetGrpcClientConn(target string) (*grpc.ClientConn, error) {
	mu.RLock()
	if c, ok := conn[target]; ok && c != nil {
		mu.RUnlock()
		return c, nil
	}
	mu.RUnlock()

	mu.Lock()
	defer mu.Unlock()

	if c, ok := conn[target]; ok && c != nil {
		return c, nil
	}

	newConn, err := NewGrpcConnection(target)
	if err != nil {
		return nil, err
	}

	conn[target] = newConn
	return newConn, nil
}
