package util

import (
	"log"
	"os"
	"path/filepath"

	"github.com/asdine/storm/v3"
	"github.com/jmoiron/sqlx"
	"github.com/mitchellh/go-homedir"
	_ "github.com/lib/pq"
)

// ConnectStorm connects to Storm database (legacy support)
func ConnectStorm(dbFile string) *storm.DB {
	if dbFile == "" {
		home, err := homedir.Dir()
		LogIfError(err, "Could not detect home directory")

		dbFile = filepath.Join(home, ".geek-life", "geek-life.db")
	}

	// Create directory if not exists
	dir := filepath.Dir(dbFile)
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err = os.MkdirAll(dir, 0755)
		LogIfError(err, "Could not create directory for DB file")
	}

	db, err := storm.Open(dbFile)
	if err != nil {
		log.Fatalf("Could not open storm DB: %v", err)
	}

	return db
}

// ConnectPostgres connects to PostgreSQL database
func ConnectPostgres(dsn string) *sqlx.DB {
	db, err := sqlx.Connect("postgres", dsn)
	if err != nil {
		log.Fatalf("Could not connect to PostgreSQL: %v", err)
	}

	// Test the connection
	if err := db.Ping(); err != nil {
		log.Fatalf("Could not ping PostgreSQL: %v", err)
	}

	return db
}

// LogIfError logs error if it's not nil
func LogIfError(err error, message string) {
	if err != nil {
		log.Printf("%s: %v", message, err)
	}
}