package service_test

import (
	"context"
	"testing"
	"time"

	"github.com/user-management-system/internal/auth"
	"github.com/user-management-system/internal/cache"
	"github.com/user-management-system/internal/domain"
	"github.com/user-management-system/internal/repository"
	"github.com/user-management-system/internal/service"
	gormsqlite "gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	_ "modernc.org/sqlite"
)

// =============================================================================
// Cache Warmup Tests - TDD approach
// =============================================================================

func setupWarmupTestEnv(t *testing.T) (*service.AuthService, *cache.CacheManager, *gorm.DB) {
	t.Helper()

	db, err := gorm.Open(gormsqlite.New(gormsqlite.Config{
		DriverName: "sqlite",
		DSN:        "file:warmup_test?mode=memory&cache=shared",
	}), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		t.Fatalf("failed to connect database: %v", err)
	}

	if err := db.AutoMigrate(&domain.User{}); err != nil {
		t.Fatalf("failed to migrate: %v", err)
	}

	userRepo := repository.NewUserRepository(db)
	jwtManager, _ := auth.NewJWTWithOptions(auth.JWTOptions{
		HS256Secret:        "test-secret",
		AccessTokenExpire:  15 * time.Minute,
		RefreshTokenExpire: 7 * 24 * time.Hour,
	})
	l1Cache := cache.NewL1Cache()
	l2Cache := cache.NewRedisCache(false)
	cacheManager := cache.NewCacheManager(l1Cache, l2Cache)
	authSvc := service.NewAuthService(userRepo, nil, jwtManager, cacheManager, 8, 5, 15*time.Minute)

	return authSvc, cacheManager, db
}

func TestAuthService_WarmupCache(t *testing.T) {
	authSvc, _, db := setupWarmupTestEnv(t)
	ctx := context.Background()

	// 创建测试用户
	db.Create(&domain.User{Username: "user1", Status: domain.UserStatusActive})
	db.Create(&domain.User{Username: "user2", Status: domain.UserStatusActive})
	db.Create(&domain.User{Username: "user3", Status: domain.UserStatusActive})

	t.Run("缓存预热成功", func(t *testing.T) {
		err := authSvc.WarmupCache(ctx, 10)
		if err != nil {
			t.Fatalf("WarmupCache failed: %v", err)
		}

		// 验证用户已缓存
		// 注意：由于缓存键格式是内部实现，这里只验证方法执行成功
		t.Log("缓存预热成功完成")
	})

	t.Run("缓存预热使用默认值", func(t *testing.T) {
		err := authSvc.WarmupCache(ctx, 0) // 0 表示使用默认值100
		if err != nil {
			t.Fatalf("WarmupCache failed: %v", err)
		}
	})

	t.Run("缓存预热限制最大值", func(t *testing.T) {
		err := authSvc.WarmupCache(ctx, 2000) // 超过1000会被限制
		if err != nil {
			t.Fatalf("WarmupCache failed: %v", err)
		}
	})
}

func TestAuthService_WarmupCache_WithEmptyDB(t *testing.T) {
	authSvc, _, _ := setupWarmupTestEnv(t)
	ctx := context.Background()

	t.Run("空数据库预热", func(t *testing.T) {
		err := authSvc.WarmupCache(ctx, 10)
		if err != nil {
			t.Fatalf("WarmupCache failed: %v", err)
		}
		// 空数据库时应该静默完成
	})
}
