package api

import (
	"encoding/json"
	"testing"
)

func TestAuthPayloadWorkerNameFallback(t *testing.T) {
	payload := map[string]string{
		"worker_name": "forged-worker-1",
		"hostname":    "DESKTOP-ABC",
	}
	data, _ := json.Marshal(payload)

	var auth struct {
		WorkerName string `json:"worker_name"`
		Worker     string `json:"worker"`
		Hostname   string `json:"hostname"`
	}
	if err := json.Unmarshal(data, &auth); err != nil {
		t.Fatal(err)
	}

	displayName := auth.WorkerName
	if displayName == "" {
		displayName = auth.Worker
	}
	if displayName == "" {
		displayName = auth.Hostname
	}
	if displayName != "forged-worker-1" {
		t.Fatalf("expected forged worker name, got %q", displayName)
	}
}

func TestShortAgentID(t *testing.T) {
	if shortAgentID("abcdef12-3456") != "abcdef12" {
		t.Fatalf("expected 8-char prefix")
	}
	if shortAgentID("ab") != "ab" {
		t.Fatalf("expected short id preserved")
	}
	if shortAgentID("") != "agent" {
		t.Fatalf("expected fallback agent label")
	}
}

func TestAgentDisplayNameFallback(t *testing.T) {
	// No hostname, no worker name — falls back to "agent-<shortID>"
	name := agentDisplayName("", "", "", "12345678-abcd")
	if name != "agent-12345678" {
		t.Fatalf("expected agent-12345678, got %q", name)
	}
}
