package shared

import (
	"fmt"
	"log"

	"gitlab.com/pactual1/backend/config"
	"gitlab.com/pactual1/backend/models"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
)


var db *gorm.DB
var err error


func Init()  error{
     host := config.AppConfig.Database.HostName
	 user := config.AppConfig.Database.UserName
	//  port := config.AppConfig.Database.Port
	 dbName := config.AppConfig.Database.DatabaseName
	 password := config.AppConfig.Database.Password

	dbString:= fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s",host,user,dbName,password) 
	// db, err = gorm.Open("postgres", "host=localhost user=postgres dbname=postgres sslmode=disable password=root")
	var err error
	// //PostgreSQL
	db, err = gorm.Open("postgres",dbString)

	if err != nil {
		log.Println("Error initializing the database: ", err)
		return err
	}
	//TODO AUTOMIGRATE models once we have them
	db.AutoMigrate(&models.User{}, &models.Company{}, &models.Device{})

	return nil

}


func GetDb() *gorm.DB {
	return db
}

func CloseDb() {
	db.Close()
}
