package internal

import (
	"context"
	"fmt"
	"log/slog"
	"os"

	"github.com/flowy-live/llink/internal/utils"
	"github.com/redis/go-redis/v9"
)

func ConnectAndTestRedis(db int) *redis.Client {
	redisHost := utils.MustGetEnv("REDIS_HOST")
	if redisHost == "" {
		slog.Error("must provide REDIS_HOST")
		os.Exit(1)
	}
	redisAddr := fmt.Sprintf("%s:%s", redisHost, "6379")
	rdb := redis.NewClient(&redis.Options{
		Addr:     redisAddr,
		Password: "", // no password set
		DB:       db,
	})

	err := rdb.Set(context.Background(), "key", "value", 0).Err()
	if err != nil {
		panic(err)
	}

	val, err := rdb.Get(context.Background(), "key").Result()
	if err != nil {
		panic(err)
	}
	slog.Debug("redis test", "key", val)
	if val != "value" {
		panic("unexpected value")
	}

	err = rdb.Del(context.Background(), "key").Err()
	if err != nil {
		panic(err)
	}

	return rdb
}
