package database

import (
	"context"
	"fmt"
	"log"
	"os"

	"git.paulbsd.com/paulbsd/ipbl/src/config"
	"git.paulbsd.com/paulbsd/ipbl/src/models"
	_ "github.com/lib/pq"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

func Initialize(ctx *context.Context, cfg *config.Config) (err error) {
	var databaseEngine = "postgres"
	var tables = []interface{}{models.IP{},
		models.Cfg{},
		models.CfgSet{},
		models.CfgTrustlist{},
		models.CfgZMQ{},
		models.HostInfo{}}

	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.DbDatabase))
	if err != nil {
		log.Fatalln(err)
	}
	cfg.Db.SetMapper(names.GonicMapper{})
	cfg.Db.ShowSQL(cfg.Switchs.Debug)

	if cfg.Switchs.Drop {
		log.Println("Dropping tables")
		cfg.Db.DropTables(tables)
		os.Exit(0)
	}

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