package db
import (
	"context"
	"fmt"
	"log"
	"time"
	"tixe/util"
	"github.com/jackc/pgx/v5/pgxpool"
)
var PgPool *pgxpool.Pool
func NewPgPool() {
	var err error
	PgPool, err = pgxpool.New(context.Background(), pgConnectionString())
	if err != nil {
		log.Fatalf("[tixe/db] Unable to create psql connection pool: '%s'", err)
	}
	log.Print("[tixe/db] Created psql pool")
	for {
		err = PgPool.Ping(context.Background())
		if err != nil {
			log.Print("[tixe/db] Database not ready, retrying in 5")
			time.Sleep(5 * time.Second)
		} else {
			log.Print("[tixe/db] Database connection verified")
			return
		}
	}
}
func pgConnectionString() string {
	user := util.LoadVar("TIXE_PSQL_USER")
	pwd := util.LoadVar("TIXE_PSQL_PASSWORD")
	host := util.LoadVar("TIXE_PSQL_HOST")
	port := util.LoadVar("TIXE_PSQL_PORT")
	db := util.LoadVar("TIXE_PSQL_DB")
	return fmt.Sprintf("postgresql://%s:%s@%s:%s/%s?sslmode=disable", user, pwd, host, port, db)
}