package database

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

	"github.com/joho/godotenv"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

// Our database
var DB *gorm.DB

// ConnectDB - 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
	}

	globals.API_RELEASE = os.Getenv("API_RELEASE")

	// 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"))
	//DBURL := "postgres://pcast:@407Smc837@177.153.50.98:5432/pcast"
	DBURL := fmt.Sprintf("%s://%s:%s@%s:%s/%s", os.Getenv("DB_DRIVER"), 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),
	// })
	db, err := gorm.Open(postgres.Open(DBURL), &gorm.Config{})

	if err != nil {
		return err
	}

	log.Println("Migrating database tables")

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

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

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

	// Count how many servers we have on the database. If none, creates our initial server.
	var servers []models.Server

	db.Find(&servers)

	if len(servers) == 0 {
		server := models.Server{
			Name: "Pcast Main Server",
			IP:   "177.153.50.98",
		}

		db.Create(&server)
	}

	// Count how many users we have on the database. If none, creates our initial admin user.
	var users []models.User

	db.Find(&users)

	if len(users) == 0 {
		passwd, _ := utils.HashPassword("123456")

		user := models.User{
			Name:        "Pcast Admin",
			Email:       "pcast@pcast.com.br",
			CompanyName: "PCast",
			Password:    passwd,
			Channel:     "PCast",
			UserType:    "A",
			Blocked:     "N",
			Cancelled:   "N",
			CreatedBy:   "Auto",
		}

		db.Create(&user)
	}

	DB = db

	return nil
}
