package database

import (
	"fmt"
	"log"
	"os"

	"git.paulbsd.com/paulbsd/pki/src/cert"
	"git.paulbsd.com/paulbsd/pki/src/config"
	"git.paulbsd.com/paulbsd/pki/src/domain"
	"git.paulbsd.com/paulbsd/pki/src/pki"
	_ "github.com/lib/pq"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

// Init creates connection to database and exec Schema
func Init(cfg *config.Config) (err error) {
	var databaseEngine = "postgres"
	tables := []interface{}{cert.Entry{},
		pki.User{}, domain.Domain{}}

	cfg.Db, err = xorm.NewEngine(databaseEngine,
		fmt.Sprintf("%s://%s:%s@%s/%s",
			databaseEngine,
			cfg.DbParams.DbUsername,
			cfg.DbParams.DbPassword,
			cfg.DbParams.DbHostname,
			cfg.DbParams.DbName))
	if err != nil {
		log.Fatalln(err)
	}
	cfg.Db.SetMapper(names.GonicMapper{})
	cfg.Db.ShowSQL(cfg.Switchs.Debug)

	if cfg.Switchs.Drop {
		for _, table := range tables {
			cfg.Db.DropTables(table)
		}
		os.Exit(0)
	}

	log.Println("Syncing tables")
	for _, table := range tables {
		cfg.Db.CreateTables(table)
		cfg.Db.Sync2(table)
	}
	return
}
