package database

import (
	"database/sql"
	"fmt"
	"log"
	"os"

	_ "github.com/mattn/go-sqlite3" // Import go-sqlite3 library
)

var (
	DBConn *sql.DB
)

// ConnectSQLite - created SQLite database connection
func ConnectSQLite(dbfile string) *sql.DB {
	log.Printf("Check if file exist - %s...", dbfile)
	_, err := os.Stat(dbfile)
	if err != nil {
		log.Printf("Creating %s...", dbfile)
		file, err := os.Create(dbfile) // Create SQLite file
		if err != nil {
			log.Fatal(err.Error())
		}
		file.Close()
		log.Printf("%s created", dbfile)
	}

	connectstring := fmt.Sprintf("file:%s?cache=shared&mode=rwc", dbfile)
	db, err := sql.Open("sqlite3", connectstring)
	if err != nil {
		log.Fatal(err.Error())
	}
	// defer db.Close()
	return db
}

// CheckTableSQLite - check if table history_data exists, and create it if it's not
func CheckTableSQLite(db *sql.DB) {
	stmt, err := db.Prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?")
	if err != nil {
		log.Fatal(err)
	}
	defer stmt.Close()
	var name string
	err = stmt.QueryRow("history_data").Scan(&name)
	if err != nil {
		sqlStmt, err := os.ReadFile("create.sql")

		_, err = db.Exec(string(sqlStmt))
		if err != nil {
			log.Printf("%q: %s", err, sqlStmt)
			return
		}
	}
}
