package database

import (
	_ "embed"
	"github.com/jmoiron/sqlx"
	_ "github.com/mattn/go-sqlite3"
	"github.com/spf13/viper"
	"log"
)

var db *sqlx.DB

//go:embed schema.sql
var schema string

func Connect() *sqlx.DB {
	if db != nil {
		return db
	}
	log.Println("Connecting to database", viper.GetString("database.path"))
	conn, err := sqlx.Connect("sqlite3", viper.GetString("database.path"))
	if err != nil {
		panic(err)
	}
	db = conn

	return conn
}

func Close() {
	db.Close()
}

func Migrate() {
	db.MustExec(schema)
}
