package repository

import (
	"database/sql"
	"log/slog"
	"os"
	"sync"
)

var (
	dbConnOnce sync.Once
	dbConn     *sql.DB
	repo       *Queries
)

func Connect(dsnURI string) {
	dbConnOnce.Do(func() {
		var err error
		dbConn, err = sql.Open("sqlite", dsnURI)
		if err != nil {
			slog.Error("Fatal error")
		}

		repo = New(dbConn)
		err = checkDBVersion(dbConn)
		if err != nil {
			slog.Error("DB Connection: Failed DB version check", "error", err)
			os.Exit(1)
		}
	})
}

func GetConnection() (*sql.DB, error) {
	if dbConn == nil {
		slog.Error("Database connection not initialized!")
	}

	return dbConn, nil
}

func GetRepository() *Queries {
	if repo == nil {
		slog.Error("Database connection not initialized!")
		os.Exit(1)
	}

	return repo
}
