package db

import (
	"database/sql"
	"fmt"
	"github.com/huandu/go-sqlbuilder"
	"xoxo-webserver/internal/env"
	// needed to import PG driver
	_ "github.com/lib/pq"
	"log/slog"
	"os"
)

var db *sql.DB

const dbFlavor = sqlbuilder.PostgreSQL

type dbConfig struct {
	host     string
	port     string
	user     string
	password string
	dbname   string
}

func (d *dbConfig) connString() string {
	return fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
		d.host, d.port, d.user, d.password, d.dbname)
}

func newDbConfig() *dbConfig {
	return &dbConfig{
		host:     env.GetOrDefault("XOXO_WEBSERVER_DB_HOST", "localhost"),
		port:     env.GetOrDefault("XOXO_WEBSERVER_DB_PORT", "5432"),
		user:     env.GetOrDefault("XOXO_WEBSERVER_DB_USER", "testuser"),
		password: env.GetOrDefault("XOXO_WEBSERVER_DB_PASSWORD", "test"),
		dbname:   env.GetOrDefault("XOXO_WEBSERVER_DB_NAME", "testdb"),
	}
}

func init() {
	sqlbuilder.DefaultFlavor = dbFlavor
	initDatabaseConnection()
	createDatabaseTablesIfNotExisting()
}

func initDatabaseConnection() {
	config := newDbConfig()
	connString := config.connString()
	var err error
	db, err = sql.Open("postgres", connString)
	if err != nil {
		slog.Error("Could not connect to db", "error", err)
		os.Exit(1)
	}
	err = db.Ping()
	if err != nil {
		slog.Error("Could not ping db", "error", err)
		os.Exit(1)
	}
	slog.Info("Connection to db successful")
}

func createDatabaseTablesIfNotExisting() {
	createJobLogTableIfNotExists()
	createQuoteTableIfNotExists()
}
