package pg

import (
	"context"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"github.com/go-pg/pg/v10"
	"github.com/go-pg/pg/v10/orm"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/models"
	liblog "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"time"
)

var DB *pg.DB
var GormDB *gorm.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(SqlGeneratePrintHook{})
	}
	if !constant.DISABLE_CREATE_TABLE {
		for _, model := range []interface{}{
			(*models.File)(nil),
			(*models.Table)(nil),
			(*models.Log)(nil),
			(*models.MappingRule)(nil),
		} {
			err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
				Temp:          false,
				IfNotExists:   true,
				FKConstraints: true,
			})
			if err != nil {
				panic(err)
			}
			//comment.AddComments(DB, model)
		}
	}

	var err error
	newLogger := logger.New(
		liblog.GormLogWriter{Module: "【StarRocks】"}, // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			Colorful:                  false,       // Disable color
		},
	)

	dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v port=%v sslmode=disable TimeZone=Asia/Shanghai",
		constant.POSTGRESQL_HOST, constant.POSTGRESQL_USER, constant.POSTGRESQL_PASSWORD, constant.POSTGRESQL_DB_NAME, constant.POSTGRESQL_PORT)
	GormDB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
		Logger: newLogger,
		//NamingStrategy: schema.NamingStrategy{
		//	TablePrefix:   "metadata.", // schema name
		//	SingularTable: false,
		//},
	})
	if err != nil {
		newLogger.Error(context.Background(), err.Error())
	}
}

type SqlGeneratePrintHook struct{}

func (hook SqlGeneratePrintHook) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) {
	return c, nil
}

func (hook SqlGeneratePrintHook) AfterQuery(c context.Context, q *pg.QueryEvent) error {
	sqlStr, err := q.FormattedQuery()
	if err != nil {
		return err
	}
	//log.Logger.Debug(string(sqlStr))
	log.Println(string(sqlStr))
	logs.Debug(string(sqlStr))
	return nil
}