package initialize

import (
	"context"
	"sundynix-go/config"
	"sundynix-go/global"

	"github.com/bsm/redislock"
	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"
)

// Redis
func Redis() {
	client, err := initRedisClient(global.Config.Redis)
	if err != nil {
		global.Logger.Error("Redis connect failed,err:", zap.Error(err))
		return
	}
	global.Redis = client
	global.Locker = redislock.New(client)
}

// 初始化Redis
func initRedisClient(redisConfig config.Redis) (redis.UniversalClient, error) {
	var client redis.UniversalClient
	//集群模式
	if redisConfig.Cluster {
		client = redis.NewClusterClient(&redis.ClusterOptions{
			Addrs:    redisConfig.ClusterAddrs,
			Password: redisConfig.Password,
		})
	} else {
		//单例模式
		client = redis.NewClient(&redis.Options{
			Addr:     redisConfig.Addr,
			Password: redisConfig.Password,
			DB:       redisConfig.DB,
		})
	}
	pong, err := client.Ping(context.Background()).Result()
	if err != nil {
		global.Logger.Error("Redis connect ping failed,err:", zap.String("name", redisConfig.Name), zap.Error(err))
		return nil, err
	}
	global.Logger.Info("Redis connect ping response:", zap.String("name", redisConfig.Name), zap.String("pong", pong))
	return client, nil
}
