// Copyright (c) 2026 Alibaba Group and its affiliates

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sdk

import (
	"runtime"
	"strings"
	"testing"
)

func TestSDKHeaderAttributesShape(t *testing.T) {
	attrs := sdkHeaderAttributes()

	if len(attrs) != 1 {
		t.Fatalf("expected exactly 1 attribute, got %d: %v", len(attrs), attrs)
	}
	ua, ok := attrs["user_agent"].(string)
	if !ok {
		t.Fatalf("user_agent missing or not a string: %v", attrs["user_agent"])
	}
	if !strings.HasPrefix(ua, SDKProduct+"/"+SDKVersion) {
		t.Fatalf("user_agent should start with %q, got %q", SDKProduct+"/"+SDKVersion, ua)
	}
	if !strings.Contains(ua, runtime.GOOS) || !strings.Contains(ua, runtime.GOARCH) {
		t.Fatalf("user_agent should embed goos/goarch, got %q", ua)
	}
}

func TestSDKHeaderAttributesNotShared(t *testing.T) {
	attrs := sdkHeaderAttributes()
	attrs["user_agent"] = "mutated"

	next := sdkHeaderAttributes()
	if next["user_agent"] == "mutated" {
		t.Fatalf("sdkHeaderAttributes reused a mutable map")
	}
}

func TestResolveVersionShape(t *testing.T) {
	v := resolveVersion()
	if !strings.HasPrefix(v, SDKVersion) {
		t.Fatalf("resolveVersion() = %q, must start with %q", v, SDKVersion)
	}
	if v == SDKVersion {
		// No VCS info — acceptable in some test environments.
		return
	}
	suffix := strings.TrimPrefix(v, SDKVersion)
	if !strings.HasPrefix(suffix, "+") {
		t.Fatalf("VCS suffix must be semver build-metadata (start with '+'), got %q", v)
	}
	rev := strings.TrimSuffix(strings.TrimPrefix(suffix, "+"), ".dirty")
	if len(rev) == 0 || len(rev) > 7 {
		t.Fatalf("commit segment should be 1-7 chars, got %q (full: %q)", rev, v)
	}
}
