package discovery

import (
	"fmt"
	"sync"
	"testing"
)

func resetInstanceIDForTest() {
	instanceID = ""
	instanceOnce = sync.Once{}
}

func TestInstanceIDStable(t *testing.T) {
	resetInstanceIDForTest()
	original := instanceIDGenerator
	defer func() {
		instanceIDGenerator = original
		resetInstanceIDForTest()
	}()

	instanceIDGenerator = func() string {
		return "fixed-id"
	}

	first := InstanceID()
	second := InstanceID()
	if first != "fixed-id" || second != "fixed-id" {
		t.Fatalf("expected stable instance id, got %q and %q", first, second)
	}
}

func TestInstanceIDRegeneratesAfterReset(t *testing.T) {
	resetInstanceIDForTest()
	original := instanceIDGenerator
	defer func() {
		instanceIDGenerator = original
		resetInstanceIDForTest()
	}()

	counter := 0
	instanceIDGenerator = func() string {
		counter++
		return fmt.Sprintf("id-%d", counter)
	}

	first := InstanceID()
	resetInstanceIDForTest()
	second := InstanceID()
	if first == second {
		t.Fatalf("expected new instance id after reset, got %q", first)
	}
}
