package cache

import (
	"context"
	"testing"
	"time"
)

func TestStoreWithoutRedisProviderUsesMemoryFallback(t *testing.T) {
	store := New(nil)
	ctx := context.Background()

	if err := store.Set(ctx, "key", "value", time.Minute); err != nil {
		t.Fatalf("Set() error = %v", err)
	}
	if value, ok, err := store.Get(ctx, "key"); err != nil || !ok || value != "value" {
		t.Fatalf("Get() = %q, %v, %v", value, ok, err)
	}
	if value, err := store.Increment(ctx, "counter", time.Minute); err != nil || value != 1 {
		t.Fatalf("Increment() = %d, %v", value, err)
	}
	if err := store.Delete(ctx, "key"); err != nil {
		t.Fatalf("Delete() error = %v", err)
	}
}

func TestStoreIncrementRecreatesExpiredKeyWithoutStaleExpiry(t *testing.T) {
	store := New(nil)
	ctx := context.Background()

	if _, err := store.Increment(ctx, "counter", time.Millisecond); err != nil {
		t.Fatalf("initial Increment() error = %v", err)
	}
	time.Sleep(5 * time.Millisecond)
	if value, err := store.Increment(ctx, "counter", 0); err != nil || value != 1 {
		t.Fatalf("expired Increment() = %d, %v", value, err)
	}
	time.Sleep(5 * time.Millisecond)
	if value, ok, err := store.Get(ctx, "counter"); err != nil || !ok || value != "1" {
		t.Fatalf("Get() after recreation = %q, %v, %v", value, ok, err)
	}
}
