package cors

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

// go test -run -v Test_NormalizeOrigin
func Test_NormalizeOrigin(t *testing.T) {
	testCases := []struct {
		origin         string
		expectedOrigin string
		expectedValid  bool
	}{
		{origin: "http://example.com", expectedValid: true, expectedOrigin: "http://example.com"},                       // Simple case should work.
		{origin: "http://example.com/", expectedValid: true, expectedOrigin: "http://example.com"},                      // Trailing slash should be removed.
		{origin: "http://example.com:3000", expectedValid: true, expectedOrigin: "http://example.com:3000"},             // Port should be preserved.
		{origin: "http://example.com:3000/", expectedValid: true, expectedOrigin: "http://example.com:3000"},            // Trailing slash should be removed.
		{origin: "app://example.com/", expectedValid: true, expectedOrigin: "app://example.com"},                        // App scheme should be accepted.
		{origin: "http://", expectedValid: false, expectedOrigin: ""},                                                   // Invalid origin should not be accepted.
		{origin: "file:///etc/passwd", expectedValid: false, expectedOrigin: ""},                                        // File scheme should not be accepted.
		{origin: "https://*example.com", expectedValid: false, expectedOrigin: ""},                                      // Wildcard domain should not be accepted.
		{origin: "http://*.example.com", expectedValid: false, expectedOrigin: ""},                                      // Wildcard subdomain should not be accepted.
		{origin: "http://example.com/path", expectedValid: false, expectedOrigin: ""},                                   // Path should not be accepted.
		{origin: "http://example.com?query=123", expectedValid: false, expectedOrigin: ""},                              // Query should not be accepted.
		{origin: "http://example.com#fragment", expectedValid: false, expectedOrigin: ""},                               // Fragment should not be accepted.
		{origin: "http://user:pass@example.com", expectedValid: false, expectedOrigin: ""},                              // Userinfo should not be accepted.
		{origin: "http://localhost", expectedValid: true, expectedOrigin: "http://localhost"},                           // Localhost should be accepted.
		{origin: "http://127.0.0.1", expectedValid: true, expectedOrigin: "http://127.0.0.1"},                           // IPv4 address should be accepted.
		{origin: "http://[::1]", expectedValid: true, expectedOrigin: "http://[::1]"},                                   // IPv6 address should be accepted.
		{origin: "http://[::1]:8080", expectedValid: true, expectedOrigin: "http://[::1]:8080"},                         // IPv6 address with port should be accepted.
		{origin: "http://[::1]:8080/", expectedValid: true, expectedOrigin: "http://[::1]:8080"},                        // IPv6 address with port and trailing slash should be accepted.
		{origin: "http://[::1]:8080/path", expectedValid: false, expectedOrigin: ""},                                    // IPv6 address with port and path should not be accepted.
		{origin: "http://[::1]:8080?query=123", expectedValid: false, expectedOrigin: ""},                               // IPv6 address with port and query should not be accepted.
		{origin: "http://[::1]:8080#fragment", expectedValid: false, expectedOrigin: ""},                                // IPv6 address with port and fragment should not be accepted.
		{origin: "http://[::1]:8080/path?query=123#fragment", expectedValid: false, expectedOrigin: ""},                 // IPv6 address with port, path, query, and fragment should not be accepted.
		{origin: "http://[::1]:8080/path?query=123#fragment/", expectedValid: false, expectedOrigin: ""},                // IPv6 address with port, path, query, fragment, and trailing slash should not be accepted.
		{origin: "http://[::1]:8080/path?query=123#fragment/invalid", expectedValid: false, expectedOrigin: ""},         // IPv6 address with port, path, query, fragment, trailing slash, and invalid segment should not be accepted.
		{origin: "http://[::1]:8080/path?query=123#fragment/invalid/", expectedValid: false, expectedOrigin: ""},        // IPv6 address with port, path, query, fragment, trailing slash, and invalid segment with trailing slash should not be accepted.
		{origin: "http://[::1]:8080/path?query=123#fragment/invalid/segment", expectedValid: false, expectedOrigin: ""}, // IPv6 address with port, path, query, fragment, trailing slash, and invalid segment with additional segment should not be accepted.
	}

	for _, tc := range testCases {
		valid, normalizedOrigin := normalizeOrigin(tc.origin)

		if valid != tc.expectedValid {
			t.Errorf("Expected origin '%s' to be valid: %v, but got: %v", tc.origin, tc.expectedValid, valid)
		}

		if normalizedOrigin != tc.expectedOrigin {
			t.Errorf("Expected normalized origin '%s' for origin '%s', but got: '%s'", tc.expectedOrigin, tc.origin, normalizedOrigin)
		}
	}
}

func Test_isOriginSerializedOrNull(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name               string
		origin             string
		expectedSerialized bool
		expectedNull       bool
	}{
		{
			name:               "literal null origin",
			origin:             "null",
			expectedSerialized: false,
			expectedNull:       true,
		},
		{
			name:               "valid http origin",
			origin:             "https://example.com",
			expectedSerialized: true,
			expectedNull:       false,
		},
		{
			name:               "valid origin with port",
			origin:             "http://example.com:8080",
			expectedSerialized: true,
			expectedNull:       false,
		},
		{
			name:               "invalid origin",
			origin:             "not-an-origin",
			expectedSerialized: false,
			expectedNull:       false,
		},
		{
			name:               "empty string",
			origin:             "",
			expectedSerialized: false,
			expectedNull:       false,
		},
		{
			name:               "origin with path is invalid",
			origin:             "https://example.com/path",
			expectedSerialized: false,
			expectedNull:       false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			isSerialized, isNull := isOriginSerializedOrNull(tt.origin)
			assert.Equal(t, tt.expectedSerialized, isSerialized, "isSerialized mismatch for origin %q", tt.origin)
			assert.Equal(t, tt.expectedNull, isNull, "isNull mismatch for origin %q", tt.origin)
		})
	}
}

// benchSubdomains builds n identical wildcard patterns for the worst-case
// (no-match) scan benchmarks below.
func benchSubdomains(n int) []subdomain {
	subs := make([]subdomain, n)
	for i := range subs {
		subs[i] = subdomain{prefix: "https://", suffix: "example.com"}
	}
	return subs
}

// Benchmark_CORS_SubdomainMatch_PerPatternNormalize reproduces the pre-PR loop,
// which ran normalizeOrigin (one url.Parse) for every pattern. allocs/op scale
// with the pattern count.
//
// go test -v -run=^$ -bench=Benchmark_CORS_SubdomainMatch_PerPatternNormalize -benchmem -count=4
func Benchmark_CORS_SubdomainMatch_PerPatternNormalize(b *testing.B) {
	subdomains := benchSubdomains(16)
	origin := "https://api.service.example.org" // matches none -> full scan

	b.ReportAllocs()

	for b.Loop() {
		for _, sub := range subdomains {
			isValid, normalized := normalizeOrigin(origin)
			if isValid && normalized == origin && sub.matchNormalized(origin) {
				break
			}
		}
	}
}

// Benchmark_CORS_MatchSubdomainOrigin normalizes once regardless of pattern
// count; allocs/op stay flat as the slice grows. Compare against
// Benchmark_CORS_SubdomainMatch_PerPatternNormalize on the same input.
//
// go test -v -run=^$ -bench=Benchmark_CORS_MatchSubdomainOrigin -benchmem -count=4
func Benchmark_CORS_MatchSubdomainOrigin(b *testing.B) {
	subdomains := benchSubdomains(16)
	origin := "https://api.service.example.org" // matches none -> full scan

	b.ReportAllocs()

	for b.Loop() {
		matchSubdomainOrigin(subdomains, origin)
	}
}

func Test_CORS_SubdomainMatch(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name     string
		sub      subdomain
		origin   string
		expected bool
	}{
		{
			name:     "match with different scheme",
			sub:      subdomain{prefix: "http://api.", suffix: "example.com"},
			origin:   "https://api.service.example.com",
			expected: false,
		},
		{
			name:     "match with different scheme",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "http://api.service.example.com",
			expected: false,
		},
		{
			name:     "match with valid subdomain",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://api.service.example.com",
			expected: true,
		},
		{
			name:     "match with valid nested subdomain",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://1.2.api.service.example.com",
			expected: true,
		},

		{
			name:     "no match with invalid prefix",
			sub:      subdomain{prefix: "https://abc.", suffix: "example.com"},
			origin:   "https://service.example.com",
			expected: false,
		},
		{
			name:     "no match with invalid suffix",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://api.example.org",
			expected: false,
		},
		{
			name:     "no match with empty origin",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "",
			expected: false,
		},
		{
			name:     "no match with malformed subdomain",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://evil.comexample.com",
			expected: false,
		},
		{
			name:     "partial match not considered a match",
			sub:      subdomain{prefix: "https://service.", suffix: "example.com"},
			origin:   "https://api.example.com",
			expected: false,
		},
		{
			name:     "no match with empty host label",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://.example.com",
			expected: false,
		},
		{
			name:     "no match with malformed host label",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://..example.com",
			expected: false,
		},
		{
			name:     "no match with malformed origin port before suffix",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://evil.com:any.example.com",
			expected: false,
		},
		{
			name:     "no match with empty label before suffix",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://foo..example.com",
			expected: false,
		},
		{
			name:     "no match with userinfo in origin",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://user@api.example.com",
			expected: false,
		},
		{
			name:     "no match with non-normalized origin",
			sub:      subdomain{prefix: "https://", suffix: "example.com"},
			origin:   "https://API.example.com",
			expected: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			got := matchSubdomainOrigin([]subdomain{tt.sub}, tt.origin)
			assert.Equal(t, tt.expected, got, "matchSubdomainOrigin()")
		})
	}
}

func Test_CORS_MatchSubdomainOrigin(t *testing.T) {
	t.Parallel()

	defaultSubs := []subdomain{
		{prefix: "https://", suffix: "example.net"},
		{prefix: "https://", suffix: "example.org"},
		{prefix: "https://", suffix: "example.com"},
	}

	tests := []struct {
		name       string
		origin     string
		subdomains []subdomain
		expected   bool
	}{
		{
			name:       "matches first pattern",
			subdomains: defaultSubs,
			origin:     "https://api.service.example.net",
			expected:   true,
		},
		{
			name:       "matches later pattern",
			subdomains: defaultSubs,
			origin:     "https://api.service.example.com",
			expected:   true,
		},
		{
			name:       "rejects invalid origin once",
			subdomains: defaultSubs,
			origin:     "https://user@api.example.com",
			expected:   false,
		},
		{
			name:       "rejects non-normalized origin",
			subdomains: defaultSubs,
			origin:     "https://API.service.example.com",
			expected:   false,
		},
		{
			name:       "rejects unmatched origin",
			subdomains: defaultSubs,
			origin:     "https://api.service.example.dev",
			expected:   false,
		},
		{
			name:       "empty slice never matches",
			subdomains: []subdomain{},
			origin:     "https://api.service.example.com",
			expected:   false,
		},
		{
			name:       "nil slice never matches",
			subdomains: nil,
			origin:     "https://api.service.example.com",
			expected:   false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			got := matchSubdomainOrigin(tt.subdomains, tt.origin)
			assert.Equal(t, tt.expected, got)
		})
	}
}
