package pg

import (
	"fmt"

	"github.com/go-pg/pg/v10"
	"github.com/go-pg/pg/v10/orm"
	"github.com/linmadan/egglib-go/persistent/pg/comment"
	"github.com/linmadan/egglib-go/persistent/pg/hooks"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/log"
)

var DB *pg.DB

func init() {
	DB = pg.Connect(&pg.Options{
		User:     constant.POSTGRESQL_USER,
		Password: constant.POSTGRESQL_PASSWORD,
		Database: constant.POSTGRESQL_DB_NAME,
		Addr:     fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
	})
	if !constant.DISABLE_SQL_GENERATE_PRINT {
		DB.AddQueryHook(hooks.SqlGeneratePrintHook{
			Logger: log.Logger,
		})
	}
	if !constant.DISABLE_CREATE_TABLE {
		tables := []interface{}{
			&models.Company{},
			&models.Department{},
			&models.User{},
			&models.ReceivedMessage{},
			&models.Role{},
			&models.RoleUser{},
			&models.Position{},
			&models.EvaluationRule{},
			&models.EvaluationTemplate{},
			&models.EvaluationCycle{},
			&models.EvaluationCycleTemplate{},
			&models.EvaluationProject{},
			&models.StaffAssess{},
			&models.StaffAssessTask{},
		}
		for _, model := range tables {
			err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
				Temp:          false,
				IfNotExists:   true,
				FKConstraints: true,
			})
			if err != nil {
				panic(err)
			}
			comment.AddComments(DB, model)
		}
	}

}