package db

import (
	"context"
	"fmt"
	"log/slog"

	pgxuuid "github.com/jackc/pgx-gofrs-uuid"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

type DbHandler struct {
	Dbpool *pgxpool.Pool
	Ctx    context.Context
}

type Configs struct {
	Host          string
	Dbname        string
	Port          string
	User          string
	Password      string
	LoggerEnabled bool
}

func NewDbHandler(configs Configs) *DbHandler {
	fmt.Println("Connecting to db")
	ctx := context.Background()

	if configs.Host == "" || configs.Dbname == "" || configs.Port == "" || configs.User == "" || configs.Password == "" {
		fmt.Println("Environment variables for database connection are not set")
		return nil
	}

	connStr := fmt.Sprintf("postgresql://%s:%s@%s:%s/%s?sslmode=disable", configs.User, configs.Password, configs.Host, configs.Port, configs.Dbname)
	fmt.Printf("Db connection string: %s\n", connStr)
	config, err := pgxpool.ParseConfig(connStr)
	if err != nil {
		panic(err)
	}

	if configs.LoggerEnabled {
		fmt.Println("Database query logging is enabled")
		config.ConnConfig.Tracer = NewMultiQueryTracer(NewLoggingQueryTracer(slog.Default()))
	}

	config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
		pgxuuid.Register(conn.TypeMap())
		return nil
	}
	dbpool, err := pgxpool.NewWithConfig(ctx, config)
	if err != nil {
		panic(err)
	}
	fmt.Println("Connected to db")

	return &DbHandler{Dbpool: dbpool, Ctx: ctx}
}
