package config

import (
	"strings"
	"testing"
)

func TestApplyEnvRedisCacheSettings(t *testing.T) {
	t.Setenv("REDIS_NAMESPACE", "tenant:prod:v2")
	t.Setenv("HAIXUN_REDIS_NAMESPACE", "")
	t.Setenv("AI_MODEL_CACHE_FINGERPRINT_SECRET", "dedicated-model-cache-secret-at-least-32-bytes")
	t.Setenv("HAIXUN_AI_MODEL_CACHE_FINGERPRINT_SECRET", "")

	var c Config
	c.ApplyEnv()
	if c.Redis.Namespace != "tenant:prod:v2" {
		t.Fatalf("namespace=%q", c.Redis.Namespace)
	}
	if c.Redis.AIModelCacheFingerprintSecret != "dedicated-model-cache-secret-at-least-32-bytes" {
		t.Fatalf("fingerprint secret environment override was not applied")
	}
}

func TestApplyEnvDefaultsRedisNamespace(t *testing.T) {
	t.Setenv("REDIS_NAMESPACE", "")
	t.Setenv("HAIXUN_REDIS_NAMESPACE", "")

	var c Config
	c.ApplyEnv()
	if c.Redis.Namespace != "haixun:dev:v1" {
		t.Fatalf("namespace=%q", c.Redis.Namespace)
	}
}

func TestApplyEnvStripeSettings(t *testing.T) {
	t.Setenv("STRIPE_ENABLED", "true")
	t.Setenv("STRIPE_SECRET_KEY", "sk_test")
	t.Setenv("STRIPE_WEBHOOK_SECRET", "whsec_test")
	t.Setenv("STRIPE_STARTER_PRICE_ID", "price_starter")
	t.Setenv("STRIPE_PRO_PRICE_ID", "price_pro")
	t.Setenv("STRIPE_SUCCESS_URL", "https://app.test/success")
	t.Setenv("STRIPE_CANCEL_URL", "https://app.test/cancel")
	t.Setenv("STRIPE_PORTAL_RETURN_URL", "https://app.test/billing")

	var c Config
	c.ApplyEnv()
	if !c.Stripe.Enabled || c.Stripe.SecretKey != "sk_test" || c.Stripe.WebhookSecret != "whsec_test" || c.Stripe.StarterPriceID != "price_starter" || c.Stripe.ProPriceID != "price_pro" || c.Stripe.SuccessURL != "https://app.test/success" || c.Stripe.CancelURL != "https://app.test/cancel" || c.Stripe.PortalReturnURL != "https://app.test/billing" {
		t.Fatalf("Stripe environment was not fully applied: %+v", c.Stripe)
	}
}

func TestApplyEnvScoutAndSeedSecrets(t *testing.T) {
	t.Setenv("SCOUT_SESSION_SECRET", "dedicated-scout-secret")
	t.Setenv("SCOUT_CRAWLER_ENDPOINT", "http://127.0.0.1:3010")
	t.Setenv("SCOUT_CRAWLER_TOKEN", "crawler-token")
	t.Setenv("SEED_ADMIN_PASSWORD", "seed-password")

	var c Config
	c.ApplyEnv()
	if c.Scout.SessionSecret != "dedicated-scout-secret" || c.Scout.CrawlerEndpoint != "http://127.0.0.1:3010" || c.Scout.CrawlerToken != "crawler-token" || c.Seed.AdminPassword != "seed-password" {
		t.Fatalf("Scout or seed environment was not fully applied")
	}
}

func TestApplyEnvInvalidPortDoesNotSkipLaterOverrides(t *testing.T) {
	t.Setenv("PORT", "invalid")
	t.Setenv("PUBLIC_WEB_BASE", "https://app.test")

	var c Config
	c.ApplyEnv()
	if c.PublicWebBase != "https://app.test" {
		t.Fatalf("invalid PORT skipped later environment overrides")
	}
}

func TestValidateProductionDependenciesRequiresDedicatedCacheSecret(t *testing.T) {
	var c Config
	c.Auth.AccessSecret = strings.Repeat("a", 40)
	c.Auth.RefreshSecret = strings.Repeat("b", 40)

	err := c.ValidateProductionDependencies()
	if err == nil || !strings.Contains(err.Error(), "AI_MODEL_CACHE_FINGERPRINT_SECRET") {
		t.Fatalf("unexpected validation error %v", err)
	}

	c.Redis.AIModelCacheFingerprintSecret = c.Auth.AccessSecret
	err = c.ValidateProductionDependencies()
	if err == nil || !strings.Contains(err.Error(), "must be dedicated") {
		t.Fatalf("unexpected reused-secret validation error %v", err)
	}
}

func TestValidateStripeEnabledConfiguration(t *testing.T) {
	valid := func(successURL string) error {
		return validateStripe(true, "sk_test_key", "whsec_test_secret", "price_starter", "price_pro", successURL, "https://app.test/app/usage/checkout?result=cancel", "https://app.test/app/usage/plans")
	}
	if err := valid("https://app.test/app/usage/checkout?result=success&checkout_id={CHECKOUT_ID}"); err != nil {
		t.Fatalf("valid Stripe configuration rejected: %v", err)
	}
	if err := valid("https://app.test/app/usage/checkout?result=success"); err == nil || !strings.Contains(err.Error(), "{CHECKOUT_ID}") {
		t.Fatalf("missing checkout token validation error = %v", err)
	}
	if err := validateStripe(true, "sk_test_key", "whsec_test_secret", "price_same", "price_same", "https://app.test/success?checkout_id={CHECKOUT_ID}", "https://app.test/cancel", "https://app.test/plans"); err == nil || !strings.Contains(err.Error(), "must differ") {
		t.Fatalf("duplicate Price ID validation error = %v", err)
	}
	if err := validateStripe(true, "sk_test_key", "whsec_test_secret", "price_starter", "price_pro", "http://app.test/success?checkout_id={CHECKOUT_ID}", "https://app.test/cancel", "https://app.test/plans"); err == nil || !strings.Contains(err.Error(), "HTTPS") {
		t.Fatalf("insecure URL validation error = %v", err)
	}
}
