package database

import (
	"api/models"
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// Our database
var DB *gorm.DB

// NewDatabase - returns a pointer to a new database connection
func ConnectDB() error {
	var erre error

	log.Println("Getting environment values")
	erre = godotenv.Load()
	if erre != nil {
		log.Printf("Error getting env, not comming through %v\n", erre)
		return erre
	}

	DBURL := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_NAME"))

	log.Println("Opening connection to database")

	db, err := gorm.Open(mysql.Open(DBURL), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})

	if err != nil {
		return err
	}

	if result := db.AutoMigrate(&models.User{}); result != nil {
		return err
	}

	// if result := db.AutoMigrate(&models.Event{}); result != nil {
	// 	return result
	// }

	DB = db

	return nil
}
