package utils

import (
	"ai_scheduler/internal/config"
	"time"

	"github.com/redis/go-redis/v9"
)

type Rdb struct {
	Rdb *redis.Client
}

var rdb *Rdb

func NewRdb(c *config.Config) *Rdb {
	if rdb == nil {
		//构建 redis
		rdbBuild := buildRdb(&c.Redis)
		//退出时清理资源
		rdb = &Rdb{Rdb: rdbBuild}
	}
	//cleanup := func() {
	//	if rdb != nil {
	//		if err := rdb.Rdb.Close(); err != nil {
	//			fmt.Println("关闭 redis 失败：%v", err)
	//		}
	//	}
	//	fmt.Println("关闭 data 中的连接资源已完成")
	//}
	return rdb
}

// buildRdb 构建redis client
func buildRdb(c *config.Redis) *redis.Client {

	rdb := redis.NewClient(&redis.Options{
		Addr:            c.Host,
		Password:        c.Pass,
		ReadTimeout:     time.Duration(c.Tls) * time.Second,
		WriteTimeout:    time.Duration(c.Tls) * time.Second,
		PoolSize:        int(c.PoolSize),
		MinIdleConns:    int(c.MaxIdle),
		ConnMaxIdleTime: time.Duration(c.MaxIdleTime) * time.Second,
		DB:              int(c.Db),
	})
	return rdb
}
