package database

import (
	"fmt"
	"log/slog"
	"net/url"

	_ "github.com/jackc/pgx/v5"
	"github.com/spf13/viper"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

var engine *xorm.Engine

func Connect() (*xorm.Engine, error) {
	if engine != nil {
		return engine, nil
	}
  dburl := url.URL{
    Scheme: "postgres",
    User: url.UserPassword(viper.GetString("db.user"), viper.GetString("db.password")),
    Host: fmt.Sprintf("%s:%d", viper.GetString("db.host"), viper.GetInt("db.port")),
    Path: fmt.Sprintf("/%s", viper.GetString("db.database")),
  }
  engi, err := xorm.NewEngine("pgx", dburl.String())
  if err != nil {
    slog.Error("Could not connect to DB", "url", dburl.Redacted(), "error", err)
    return nil, err
  }
  engi.SetMapper(names.LintGonicMapper)
  err = engi.Sync(new(User), new(File))
  if err != nil {
    slog.Error("Error syncing DB schema", "error", err)
  }
  engine = engi

  return engi, nil
}

