package validator

import (
	"testing"
)

// Simplified comprehensive test for JWT secret validation
func TestJWTSecretValidation(t *testing.T) {
	validator := NewCredentialValidator()

	// Good secrets - these should pass
	goodSecrets := []struct {
		name   string
		secret string
		env    string
	}{
		{
			name:   "Good 32-char for dev",
			secret: "ima7xR+9nT0Yz0jKVu/QwtkqdAaU+3Ki",
			env:    "development",
		},
		{
			name:   "Good 64-char for prod",
			secret: "1WDduocStecRuIv+Us1t/RnYDoW1ZcEEbU+H+WykJG+IT5WnijzBb8uUPzGKju+D",
			env:    "production",
		},
	}

	for _, tt := range goodSecrets {
		t.Run(tt.name, func(t *testing.T) {
			err := validator.ValidateJWTSecret(tt.secret, tt.env)
			if err != nil {
				t.Errorf("Expected no error for valid secret, got: %v", err)
			}
		})
	}

	// Bad secrets - these should fail
	badSecrets := []struct {
		name      string
		secret    string
		env       string
		mustContain string
	}{
		{
			name:        "Too short",
			secret:      "short",
			env:         "development",
			mustContain: "too short",
		},
		{
			name:        "Common weak - password",
			secret:      "password-is-not-secure-but-32char",
			env:         "development",
			mustContain: "common weak value",
		},
		{
			name:        "Dangerous pattern",
			secret:      "please-change-this-ima7xR+9nT0Yz",
			env:         "development",
			mustContain: "suspicious pattern",
		},
		{
			name:        "Repeating characters",
			secret:      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
			env:         "development",
			mustContain: "consecutive repeating characters",
		},
		{
			name:        "Sequential pattern",
			secret:      "abcdefghijklmnopqrstuvwxyzabcdef",
			env:         "development",
			mustContain: "sequential patterns",
		},
		{
			name:        "Low entropy",
			secret:      "abababababababababababababababab",
			env:         "development",
			mustContain: "insufficient entropy",
		},
		{
			name:        "Prod too short",
			secret:      "ima7xR+9nT0Yz0jKVu/QwtkqdAaU+3Ki",
			env:         "production",
			mustContain: "too short for production",
		},
	}

	for _, tt := range badSecrets {
		t.Run(tt.name, func(t *testing.T) {
			err := validator.ValidateJWTSecret(tt.secret, tt.env)
			if err == nil {
				t.Errorf("Expected error containing '%s', got no error", tt.mustContain)
			} else if !contains(err.Error(), tt.mustContain) {
				t.Errorf("Expected error containing '%s', got: %v", tt.mustContain, err)
			}
		})
	}
}

func contains(s, substr string) bool {
	return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
		(len(s) > 0 && len(substr) > 0 && findSubstring(s, substr)))
}

func findSubstring(s, substr string) bool {
	for i := 0; i <= len(s)-len(substr); i++ {
		if s[i:i+len(substr)] == substr {
			return true
		}
	}
	return false
}
