package app

import (
	"strings"
	"testing"

	"hyapp/services/gateway-service/internal/config"
	httptransport "hyapp/services/gateway-service/internal/transport/http"
)

func TestConfigureAuthRateLimitRequiresRedisAddrWhenEnabled(t *testing.T) {
	handler := httptransport.NewHandler(nil)
	_, err := configureAuthRateLimit(handler, config.AuthRateLimitConfig{
		Enabled: true,
	}, httptransport.AuthRateLimitConfig{Enabled: true})
	if err == nil || !strings.Contains(err.Error(), "redis_addr") {
		t.Fatalf("enabled auth rate limit must require redis_addr, err=%v", err)
	}
}

func TestConfigureAuthRateLimitDisabledDoesNotRequireRedis(t *testing.T) {
	handler := httptransport.NewHandler(nil)
	closeRedis, err := configureAuthRateLimit(handler, config.AuthRateLimitConfig{
		Enabled: false,
	}, httptransport.AuthRateLimitConfig{Enabled: false})
	if err != nil {
		t.Fatalf("disabled auth rate limit should not connect redis: %v", err)
	}
	if closeRedis != nil {
		t.Fatal("disabled auth rate limit must not allocate redis client")
	}
}

func TestConfigureGiftCapacityLimitRequiresRedisAddrWhenEnabled(t *testing.T) {
	handler := httptransport.NewHandler(nil)
	_, err := configureGiftCapacityLimit(handler, config.GiftCapacityLimitConfig{Enabled: true})
	if err == nil || !strings.Contains(err.Error(), "redis_addr is required") {
		t.Fatalf("enabled gift capacity limit must require redis_addr, err=%v", err)
	}
}

func TestConfigureGiftCapacityLimitDisabledDoesNotRequireRedis(t *testing.T) {
	handler := httptransport.NewHandler(nil)
	closeRedis, err := configureGiftCapacityLimit(handler, config.GiftCapacityLimitConfig{Enabled: false})
	if err != nil {
		t.Fatalf("disabled gift capacity limit should not connect redis: %v", err)
	}
	if closeRedis != nil {
		t.Fatal("disabled gift capacity limit must not allocate redis client")
	}
}

func TestConfigureLoginRiskRequiresSessionDenylistRedisEvenWhenRiskDisabled(t *testing.T) {
	handler := httptransport.NewHandler(nil)
	_, err := configureLoginRisk(handler, config.LoginRiskConfig{Enabled: false}, httptransport.LoginRiskConfig{Enabled: false})
	if err == nil || !strings.Contains(err.Error(), "session denylist redis_addr is required") {
		t.Fatalf("mandatory session denylist must reject empty Redis config, err=%v", err)
	}
}

func TestConfigureLoginRiskFailsStartupWhenSessionDenylistRedisUnavailable(t *testing.T) {
	handler := httptransport.NewHandler(nil)
	_, err := configureLoginRisk(handler, config.LoginRiskConfig{
		Enabled:   false,
		RedisAddr: "127.0.0.1:1",
	}, httptransport.LoginRiskConfig{Enabled: false})
	if err == nil || !strings.Contains(err.Error(), "connect session denylist redis") {
		t.Fatalf("unreachable session denylist Redis must fail startup, err=%v", err)
	}
}
