// pkg/redisclient/redis.go

package redisclient

import (
	"context"
	"fmt"
	"os"

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

var RDB *redis.Client

func Init() {
	redisHost := os.Getenv("REDIS_HOST")
	if redisHost == "" {
		redisHost = "localhost"
	}

	redisPort := os.Getenv("REDIS_PORT")
	if redisPort == "" {
		redisPort = "6379"
	}

	redisPassword := os.Getenv("REDIS_PASSWORD")
	if redisPassword == "" {
		redisPassword = ""
	}

	// Configure Redis client with security settings
	opts := &redis.Options{
		Addr:             fmt.Sprintf("%s:%s", redisHost, redisPort),
		Password:         redisPassword,
		DB:               0,
		DisableIndentity: true, // Disable client-side caching to prevent protocol confusion
		IdentitySuffix:   "",   // Disable identity suffix
	}

	RDB = redis.NewClient(opts)

	// Test connection with authentication
	ctx := context.Background()
	if _, err := RDB.Ping(ctx).Result(); err != nil {
		panic(fmt.Sprintf("Could not connect to Redis: %v", err))
	}

	// Log connection security status
	if redisPassword != "" {
		fmt.Println("✓ Redis connection secured with password authentication")
	} else {
		fmt.Println("⚠ WARNING: Redis connection without password - security risk!")
	}
}
