package data

import (
	"center-api/internal/conf"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	_ "github.com/go-sql-driver/mysql"
	"github.com/redis/go-redis/v9"
)

// Data .
type Data struct {
	Rdb *redis.Client
}

// NewData .
func NewData(c *conf.Bootstrap, hLog *log.Helper) (*Data, func(), error) {
	//构建 redis
	rdb := buildRdb(c)
	//退出时清理资源
	cleanup := func() {
		if rdb != nil {
			if err := rdb.Close(); err != nil {
				hLog.Error("关闭 redis 失败：", err)
			}
		}
		fmt.Println("关闭 data 中的连接资源已完成")
	}
	return &Data{Rdb: rdb}, cleanup, nil
}

// buildRdb 构建redis client
func buildRdb(c *conf.Bootstrap) *redis.Client {
	if c.Data == nil || c.Data.Redis == nil {
		return nil
	}
	rdb := redis.NewClient(&redis.Options{
		Addr:            c.Data.Redis.Addr,
		Password:        c.Data.Redis.Password,
		ReadTimeout:     c.Data.Redis.ReadTimeout.AsDuration(),
		WriteTimeout:    c.Data.Redis.WriteTimeout.AsDuration(),
		PoolSize:        int(c.Data.Redis.PoolSize),
		MinIdleConns:    int(c.Data.Redis.MinIdleConns),
		ConnMaxIdleTime: c.Data.Redis.ConnMaxIdleTime.AsDuration(),
		DB:              0,
	})
	return rdb
}
