package config

import (
	"os"
	"path/filepath"
	"testing"
	"time"
)

func TestDefaultConfigPreparedCache(t *testing.T) {
	cfg := DefaultConfig()
	if cfg.Executor.PreparedCacheMaxStatements != 10000 {
		t.Fatalf("default prepared_cache_max_statements = %d, want 10000", cfg.Executor.PreparedCacheMaxStatements)
	}
	if cfg.Executor.PreparedCacheIdleTTL != time.Hour {
		t.Fatalf("default prepared_cache_idle_ttl = %v, want 1h", cfg.Executor.PreparedCacheIdleTTL)
	}
}

func TestLoadConfigPreparedCacheDefaultsWhenUnset(t *testing.T) {
	path := writeTempConfig(t, "executor:\n  protocol_mode: strict_cassandra\n")
	cfg, err := LoadConfig(path)
	if err != nil {
		t.Fatalf("LoadConfig: %v", err)
	}
	if cfg.Executor.PreparedCacheMaxStatements != 10000 {
		t.Fatalf("unset prepared_cache_max_statements should default to 10000, got %d", cfg.Executor.PreparedCacheMaxStatements)
	}
	if cfg.Executor.PreparedCacheIdleTTL != time.Hour {
		t.Fatalf("unset prepared_cache_idle_ttl should default to 1h, got %v", cfg.Executor.PreparedCacheIdleTTL)
	}
}

func TestLoadConfigPreparedCacheExplicitValues(t *testing.T) {
	path := writeTempConfig(t, "executor:\n  prepared_cache_max_statements: 250\n  prepared_cache_idle_ttl: 30m\n")
	cfg, err := LoadConfig(path)
	if err != nil {
		t.Fatalf("LoadConfig: %v", err)
	}
	if cfg.Executor.PreparedCacheMaxStatements != 250 {
		t.Fatalf("explicit prepared_cache_max_statements = %d, want 250", cfg.Executor.PreparedCacheMaxStatements)
	}
	if cfg.Executor.PreparedCacheIdleTTL != 30*time.Minute {
		t.Fatalf("explicit prepared_cache_idle_ttl = %v, want 30m", cfg.Executor.PreparedCacheIdleTTL)
	}
}

func writeTempConfig(t *testing.T, body string) string {
	t.Helper()
	dir := t.TempDir()
	path := filepath.Join(dir, "config.yaml")
	if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
		t.Fatalf("write temp config: %v", err)
	}
	return path
}
