package services

import (
	"github.com/pkg/errors"
	"sync"

	"github.com/fiskerinc/cloud-services/pkg/clickhouse"
)

var (
	client    clickhouse.ClientInterface
	clickLock sync.Mutex
)

// GetClickhouseClient returns singleton instance of clickhouse client
func GetClickhouseClient() (clickhouse.ClientInterface, error) {
	if client != nil {
		return client, nil
	}

	clickLock.Lock()
	defer clickLock.Unlock()

	var err error
	if client == nil {
		conn, err := clickhouse.NewConn()
		if err != nil {
			return nil, errors.WithStack(err)
		}

		client, err = clickhouse.NewClient(conn)
	}

	return client, err
}
