package services

import (
	"sync"

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

var (
	clickhouseClient   clickhouse.ClientInterface
	clickhouseConn     clickhouse.ConnInterface
	clickhouseConnLock sync.Mutex
)

func initClickhouseConn() (clickhouse.ConnInterface, error) {
	logger.Info().Msg("Init clickhouse connection")

	clickhouseConnLock.Lock()
	defer clickhouseConnLock.Unlock()

	clClient, err := clickhouse.NewConn()
	if err != nil {
		logger.Error().Err(err).Msg("cannot connect to clickhouse")
		return nil, errors.WithMessage(err, "cannot connect to clickhouse")
	}

	clickhouseConn = clClient

	return clickhouseConn, nil
}

func GetClickhouseConn() (clickhouse.ConnInterface, error) {
	if clickhouseConn != nil {
		return clickhouseConn, nil
	}

	return initClickhouseConn()
}

func SetClickhouseConn(conn clickhouse.ConnInterface) {
	clickhouseConnLock.Lock()
	defer clickhouseConnLock.Unlock()

	clickhouseConn = conn
}

func GetClickhouseClient() (clickhouse.ClientInterface, error) {
	if clickhouseClient != nil {
		return clickhouseClient, nil
	}

	conn, err := GetClickhouseConn()
	if err != nil {
		return nil, err
	}

	return clickhouse.NewClient(conn)
}
