package config

import (
	"fmt"
	"strings"
	"testing"
)

func TestLoadIdentitySecretStoreUsesNewEnvironmentNamesAndIgnoresLegacyBusinessValues(t *testing.T) {
	t.Setenv("IDENTITY_SECRET_STORE", "file")
	t.Setenv("IDENTITY_SECRET_DIR", ".test-secrets/identity")
	t.Setenv("OIDC_ISSUER", "https://legacy-sensitive.example/issuer")
	t.Setenv("OIDC_INTROSPECTION_CLIENT_SECRET", "legacy-sensitive-secret")
	t.Setenv("OIDC_SESSION_ENCRYPTION_KEY", "legacy-sensitive-session-key")

	cfg := Load()
	if cfg.IdentitySecretStore != "file" || cfg.IdentitySecretDir != ".test-secrets/identity" {
		t.Fatalf("identity SecretStore = %q %q", cfg.IdentitySecretStore, cfg.IdentitySecretDir)
	}
	printed := fmt.Sprintf("%+v", cfg)
	for _, legacyValue := range []string{"legacy-sensitive.example", "legacy-sensitive-secret", "legacy-sensitive-session-key"} {
		if strings.Contains(printed, legacyValue) {
			t.Fatalf("legacy identity business setting was loaded into Config: %q", legacyValue)
		}
	}
}

func TestValidateIdentityFileSecretStoreRequiresDirectory(t *testing.T) {
	cfg := Config{IdentitySecretStore: "file"}
	if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "IDENTITY_SECRET_DIR") {
		t.Fatalf("Validate() error = %v, want missing identity secret directory", err)
	}
	cfg.IdentitySecretDir = ".test-secrets/identity"
	if err := cfg.Validate(); err != nil {
		t.Fatalf("valid file SecretStore was rejected: %v", err)
	}
}

func TestValidateIdentityKubernetesSecretStore(t *testing.T) {
	cfg := Config{IdentitySecretStore: "kubernetes", IdentityKubernetesSecretName: "easyai-gateway-identity"}
	if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "namespace") {
		t.Fatalf("Validate() error = %v, want missing namespace", err)
	}
	cfg.IdentityKubernetesNamespace = "easyai"
	if err := cfg.Validate(); err != nil {
		t.Fatalf("valid Kubernetes SecretStore was rejected: %v", err)
	}
}

func TestValidateIdentitySecurityEventTiming(t *testing.T) {
	cfg := Config{
		IdentitySecurityEventHeartbeatIntervalSeconds: 60,
		IdentitySecurityEventStaleAfterSeconds:        60,
		IdentitySecurityEventClockSkewSeconds:         60,
	}
	if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "heartbeat") {
		t.Fatalf("Validate() error = %v, want invalid stale threshold", err)
	}
}
