package clickhouse

import (
	"database/sql"
	"fmt"

	_ "github.com/ClickHouse/clickhouse-go/v2"
)

// ClickHouseOpen connects to a ClickHouse server and returns a *sql.DB.
// Constructs a DSN of the form:
//
//	clickhouse://user:password@host:port/database
func ClickHouseOpen(host string, port int, user, password, database string) (*sql.DB, error) {
	dsn := fmt.Sprintf("clickhouse://%s:%s@%s:%d/%s", user, password, host, port, database)
	db, err := sql.Open("clickhouse", dsn)
	if err != nil {
		return nil, fmt.Errorf("clickhouse_open: open: %w", err)
	}
	if err := db.Ping(); err != nil {
		db.Close()
		return nil, fmt.Errorf("clickhouse_open: ping %s:%d/%s: %w", host, port, database, err)
	}
	return db, nil
}
