package db

import (
	"context"
	"log/slog"
	"os"

	"github.com/jackc/pgx/v5/pgxpool"
)

var db *pgxpool.Pool

func Cleanup() {
	db.Close()
}

func Pool() *pgxpool.Pool {
	return db
}

func Init() {
	connString := os.Getenv("LLINK_POSTGRES_CONNECTION_URL")
	if connString == "" {
		slog.Error("must provide LLINK_POSTGRES_CONNECTION_URL in env")
		os.Exit(1)
	}

	dbpool, err := pgxpool.New(context.Background(), connString)
	if err != nil {
		slog.Error("unable to create connection pool", "error", err)
		os.Exit(1)
	}

	var greeting string
	err = dbpool.QueryRow(context.Background(), "select 'Hello, world!'").Scan(&greeting)
	if err != nil {
		slog.Error("queryRow failed", "error", err)
		os.Exit(1)
	}

	slog.Info("successfully connected to database", "greeting", greeting)

	db = dbpool
}
