package data

import (
  "log"
  "database/sql"
  "github.com/gofiber/fiber/v2"
   _ "github.com/mattn/go-sqlite3"
   "github.com/jmoiron/sqlx"
 )

var configured bool
var DB *sqlx.DB

func Setup(driver string, url string) {
  if(!configured) {
    var err error

    DB, err = sqlx.Connect(driver, url)
    if err != nil {
        log.Fatalln(err)
    }
    configured = true;
  }
}

func Shutdown() {
  DB.Close()
}

func SelectJson[T any](c *fiber.Ctx, err error, sql string, args ...interface{}) error {
  var result []T
  if err != nil { goto fail }

  err = DB.Select(&result, sql, args...)
  if err != nil { goto fail }

  return c.JSON(&result)

fail: return err
}

func GetJson[T any](c *fiber.Ctx, err error, sql string, args ...interface{}) error {
  var result T
  if err != nil { goto fail }

  err = DB.Get(&result, sql, args...)
  if err != nil { goto fail }

  return c.JSON(&result)

fail: return err
}

func Exec(err error, sql_query string, args ...interface{}) (sql.Result, error) {
  if err != nil { return nil, err }
  result, err := DB.Exec(sql_query, args...)
  return result, err
}
