package ratelimit

import (
	"context"
	"testing"
	"time"

	"git3.techno-world.net/lrosales/broad-announce/internal/store"
)

func newRedis(t *testing.T) *store.Redis {
	t.Helper()
	r, err := store.ConnectRedis(context.Background(), "redis://localhost:6379/0")
	if err != nil {
		t.Skipf("redis not available: %v", err)
	}
	return r
}

func TestAllow_UnderCap(t *testing.T) {
	r := newRedis(t)
	l := New(r.Client)
	for i := 0; i < 5; i++ {
		ok, _, err := l.Allow(context.Background(), "test-under-"+time.Now().Format(time.RFC3339Nano), 100)
		if err != nil {
			t.Fatal(err)
		}
		if !ok {
			t.Fatalf("denied at i=%d under cap", i)
		}
	}
}

func TestAllow_OverCap(t *testing.T) {
	r := newRedis(t)
	l := New(r.Client)
	key := "test-over-" + time.Now().Format(time.RFC3339Nano)
	// cap=2, try 5 in one second
	for i := 0; i < 2; i++ {
		ok, _, _ := l.Allow(context.Background(), key, 2)
		if !ok {
			t.Fatalf("denied at i=%d", i)
		}
	}
	ok, ttl, _ := l.Allow(context.Background(), key, 2)
	if ok {
		t.Fatal("expected deny at i=3")
	}
	if ttl <= 0 || ttl > 2*time.Second {
		t.Fatalf("ttl out of range: %v", ttl)
	}
}

func TestAllow_ZeroCapIsNoOp(t *testing.T) {
	r := newRedis(t)
	l := New(r.Client)
	for i := 0; i < 1000; i++ {
		ok, _, _ := l.Allow(context.Background(), "noop", 0)
		if !ok {
			t.Fatal("zero cap must always allow")
		}
	}
}
