package data

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"voucher/internal/conf"
)

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

// NewRdb .
func NewRdb(c *conf.Bootstrap) (*Rdb, func(), error) {
	//构建 redis
	rdb, err := buildRdb(c.Data.Redis)
	if err != nil {
		return nil, nil, err
	}

	//退出时清理资源
	cleanup := func() {
		if rdb != nil {
			if err := rdb.Close(); err != nil {
				fmt.Printf("关闭rdb redis 失败：%v", err)
			}
		}
		fmt.Println("关闭 redis 中的连接资源已完成")
	}
	return &Rdb{Rdb: rdb}, cleanup, nil
}

// buildRdb 构建redis client
func buildRdb(c *conf.Data_Redis) (*redis.Client, error) {
	rdb := redis.NewClient(&redis.Options{
		Addr:            c.Addr,
		Password:        c.Password,
		ReadTimeout:     c.ReadTimeout.AsDuration(),
		WriteTimeout:    c.WriteTimeout.AsDuration(),
		PoolSize:        int(c.PoolSize),
		MinIdleConns:    int(c.MinIdleConns),
		ConnMaxIdleTime: c.ConnMaxIdleTime.AsDuration(),
		DB:              int(c.Db),
	})

	_, err := rdb.Ping(context.Background()).Result()
	if err != nil {
		fmt.Printf("redis 连接失败：%v", err)
	}

	return rdb, err
}
