package utils

import (
	"context"
	"sync"
	"testing"
)

func TestGetGID(t *testing.T) {
	gid := getGID()
	if gid <= 0 {
		t.Errorf("Expected positive GID, got %d", gid)
	}

	var wg sync.WaitGroup
	wg.Add(2)
	var g1, g2 int64

	go func() {
		defer wg.Done()
		g1 = getGID()
	}()

	go func() {
		defer wg.Done()
		g2 = getGID()
	}()

	wg.Wait()

	if g1 <= 0 || g2 <= 0 {
		t.Errorf("Expected positive GIDs, got %d and %d", g1, g2)
	}
	if g1 == gid || g2 == gid || g1 == g2 {
		t.Errorf("Expected distinct goroutine IDs, got main=%d, g1=%d, g2=%d", gid, g1, g2)
	}
}

func TestGLSStoreAndLoad(t *testing.T) {
	ctx := context.WithValue(context.Background(), "test_key", "test_val")
	SetContext(ctx)
	defer ClearContext()

	retrieved := GetContext()
	if retrieved == nil {
		t.Fatal("Expected non-nil context")
	}
	if val := retrieved.Value("test_key"); val != "test_val" {
		t.Errorf("Expected 'test_val', got %v", val)
	}
}

func BenchmarkGetGID(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		getGID()
	}
}
