package operation

import (
	"game/common/constant"
	"game/common/model/user"
	"game/common/utils"
	"game/server/db/config"
	"github.com/fox/fox/db"
	"github.com/fox/fox/log"
	"github.com/go-redis/redis/v8"
	"gorm.io/gorm"
)

var (
	UserRedis    *redis.Client
	AccountRedis *redis.Client
	UserDB       *gorm.DB
	LogDB        *gorm.DB
)

func InitRedis() {
	log.Debug("init redis")
	var err error
	cfg := &config.Cfg.Redis
	UserRedis, err = db.InitRedis(cfg.Password, cfg.Host, cfg.Port, constant.Redis1User)
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	utils.AutoSetRedisPool(UserRedis)
	AccountRedis, err = db.InitRedis(cfg.Password, cfg.Host, cfg.Port, constant.Redis2Account)
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	utils.AutoSetRedisPool(AccountRedis)
}

func InitDb() {
	log.Debug("init db")
	var err error
	cfg := &config.Cfg.UserDb
	UserDB, err = db.InitMysql(cfg.Username, cfg.Password, cfg.Host, cfg.Port, cfg.DbName)
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	// 自动迁移game库表结构
	err = UserDB.AutoMigrate(
		&user.UserAccount{},
		&user.User{},
		&user.UserResources{},
	)
	if err != nil {
		log.Fatal(err.Error())
		return
	}

	cfgClickhouse := &config.Cfg.LogDb
	LogDB, err = db.InitClickHouse(cfgClickhouse.Host, cfgClickhouse.Port, cfgClickhouse.Username, cfgClickhouse.Password, cfgClickhouse.DbName)
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	// 自动迁移game_log库表结构
	if err1 := db.AutoMigrateClickHouse(LogDB, user.UserLoginLog{}.TableOptions(), user.UserLoginLog{}); err1 != nil {
		err = err1
	}
	if err1 := db.AutoMigrateClickHouse(LogDB, user.GameRecordLog{}.TableOptions(), user.GameRecordLog{}); err == nil && err1 != nil {
		err = err1
	}
	if err1 := db.AutoMigrateClickHouse(LogDB, user.UserRecordLog{}.TableOptions(), user.UserRecordLog{}); err == nil && err1 != nil {
		err = err1
	}
	if err1 := db.AutoMigrateClickHouse(LogDB, user.UserResourcesLog{}.TableOptions(), user.UserResourcesLog{}); err == nil && err1 != nil {
		err = err1
	}

	if err != nil {
		log.Fatal(err.Error())
		return
	}
}
