package mysql

import (
	"context"
	"testing"
	"time"

	"wucher/internal/domain/transient"
)

func TestTokenStore_SetGetDelete(t *testing.T) {
	db := openDBTestSQLite(t)
	if err := AutoMigrate(db); err != nil {
		t.Fatalf("auto migrate: %v", err)
	}

	baseTime := time.Date(2026, 3, 20, 10, 0, 0, 0, time.UTC)
	store := NewTokenStore(db)
	store.now = func() time.Time { return baseTime }

	ctx := context.Background()
	if err := store.Set(ctx, "auth:test", []byte("value"), time.Minute); err != nil {
		t.Fatalf("set: %v", err)
	}

	got, err := store.Get(ctx, "auth:test")
	if err != nil {
		t.Fatalf("get: %v", err)
	}
	if string(got) != "value" {
		t.Fatalf("unexpected value %q", got)
	}

	store.now = func() time.Time { return baseTime.Add(2 * time.Minute) }
	got, err = store.Get(ctx, "auth:test")
	if err != nil {
		t.Fatalf("get expired: %v", err)
	}
	if got != nil {
		t.Fatalf("expected expired value to be cleared, got %q", got)
	}

	var count int64
	if err := db.Model(&transient.TokenEntry{}).Where("store_key = ?", "auth:test").Count(&count).Error; err != nil {
		t.Fatalf("count expired token: %v", err)
	}
	if count != 0 {
		t.Fatalf("expected expired token deleted, got %d rows", count)
	}

	store.now = func() time.Time { return baseTime }
	if err := store.Set(ctx, "auth:persistent", []byte("keep"), 0); err != nil {
		t.Fatalf("set persistent: %v", err)
	}
	store.now = func() time.Time { return baseTime.Add(24 * time.Hour) }
	got, err = store.Get(ctx, "auth:persistent")
	if err != nil {
		t.Fatalf("get persistent: %v", err)
	}
	if string(got) != "keep" {
		t.Fatalf("unexpected persistent value %q", got)
	}

	if err := store.Delete(ctx, "auth:persistent"); err != nil {
		t.Fatalf("delete: %v", err)
	}
	got, err = store.Get(ctx, "auth:persistent")
	if err != nil {
		t.Fatalf("get after delete: %v", err)
	}
	if got != nil {
		t.Fatalf("expected deleted value to be nil, got %q", got)
	}

	got, err = store.Get(ctx, "auth:missing")
	if err != nil {
		t.Fatalf("get missing: %v", err)
	}
	if got != nil {
		t.Fatalf("expected missing value to be nil, got %q", got)
	}
}
