package database

import (
	"fmt"

	sashimi "git.sharkk.net/Sharkk/Sashimi"
)

var db *sashimi.DB

// Init initializes the database connection
func Init(dbPath string) error {
	var err error
	db, err = sashimi.New(dbPath)
	if err != nil {
		return fmt.Errorf("failed to initialize database: %w", err)
	}
	return nil
}

// DB returns the global database connection
func DB() *sashimi.DB {
	if db == nil {
		panic("database not initialized - call Init() first")
	}
	return db
}

// Close closes the database connection
func Close() error {
	if db != nil {
		return db.Close()
	}
	return nil
}

// Wrapper functions for convenience
func Query(query string, args ...any) (*sashimi.Stmt, error) {
	return db.Query(query, args...)
}

func Get(dest any, query string, args ...any) error {
	return db.Get(dest, query, args...)
}

func Select(dest any, query string, args ...any) error {
	return db.Select(dest, query, args...)
}

func Exec(query string, args ...any) error {
	return db.Exec(query, args...)
}

func Update(tableName string, fields map[string]any, whereField string, whereValue any) error {
	return db.Update(tableName, fields, whereField, whereValue)
}

func Insert(tableName string, obj any, excludeFields ...string) (int64, error) {
	return db.Insert(tableName, obj, excludeFields...)
}

func Transaction(fn func() error) error {
	return db.Transaction(fn)
}
