package storage

import (
	"context"
	"fmt"
	"os"

	"github.com/ClickHouse/clickhouse-go/v2"
	"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
)

var Connection driver.Conn

func Connect() error {
	conn, err := connect()
	if err != nil {
		return err
	}
	Connection = *conn
	return nil
}

func connect() (*driver.Conn, error) {
	var (
		ctx = context.Background()
		conn, err = clickhouse.Open(&clickhouse.Options{
			Addr: []string{"clickhouse:9000"},
			Auth: clickhouse.Auth{
				Database: "monitoring",
				Username: "default",
				Password: os.Getenv("CLICKHOUSE_PASSWORD"),
			},
			TLS: nil,
		})
	)

	if err != nil {
		return nil, err
	}

	if err := conn.Ping(ctx); err != nil {
		if exception, ok := err.(*clickhouse.Exception); ok {
			fmt.Printf("Exception [%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace)
		}
		return nil, err
	}
	return &conn, nil
}