package redis

import (
	"context"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
)

// ProvideRedisUniversalClient provides a Redis UniversalClient for Wire DI
// This is needed for components like leader election that require the raw Redis client
func ProvideRedisUniversalClient(cfg *config.Config, logger *zap.Logger) (redis.UniversalClient, error) {
	logger = logger.Named("RedisClient")

	// Create Redis client
	client := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", cfg.Cache.Host, cfg.Cache.Port),
		Password: cfg.Cache.Password,
		DB:       cfg.Cache.DB,
	})

	// Test connection
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if _, err := client.Ping(ctx).Result(); err != nil {
		logger.Error("Failed to connect to Redis", zap.Error(err))
		return nil, fmt.Errorf("redis connection failed: %w", err)
	}

	logger.Info("✅ Redis client connected successfully",
		zap.String("host", cfg.Cache.Host),
		zap.Int("port", cfg.Cache.Port),
		zap.Int("db", cfg.Cache.DB))

	return client, nil
}
