package localapi

import (
	"io"
	"log/slog"
	"testing"
)

// v0.82.0 version channel: EVERY local-API response carries X-Felhom-Agent-Version with the
// injected version — the controller's capability comparison source. Asserted across an authed
// route, an UNAUTHED request (the middleware wraps auth), and a 404 route, so no response class
// can silently lose the header. Companion red-proof: drop the Handler() wrap (return mux) → every
// row fails with an empty header.
func TestVersionHeader_OnEveryResponse(t *testing.T) {
	srv, err := NewServer(Options{
		ListenAddr:   "127.0.0.1:0",
		AgentVersion: "9.9.9-test",
		Guests:       &fakeGuests{},
		Backups:      &fakeBackups{},
		Store:        &fakeStore{},
		Storage:      fakeStorage{},
		Tokens:       staticTokens{"A": 8200},
		Logger:       slog.New(slog.NewTextHandler(io.Discard, nil)),
	})
	if err != nil {
		t.Fatalf("new server: %v", err)
	}
	h := srv.Handler()
	for _, tc := range []struct {
		name, method, path, token string
	}{
		{"authed route", "GET", "/storage", "A"},
		{"unauthed request", "GET", "/storage", ""},
		{"unknown route", "GET", "/nonexistent", "A"},
	} {
		t.Run(tc.name, func(t *testing.T) {
			w := do(t, h, tc.method, tc.path, tc.token, "")
			if got := w.Header().Get("X-Felhom-Agent-Version"); got != "9.9.9-test" {
				t.Errorf("X-Felhom-Agent-Version = %q, want %q (status %d)", got, "9.9.9-test", w.Code)
			}
		})
	}
}

// An empty AgentVersion (misconfigured/test construction) must not emit an empty header.
func TestVersionHeader_OmittedWhenUnset(t *testing.T) {
	srv := newNetServer(t, &fakeNetOps{}, t.TempDir()) // helper does not set AgentVersion
	w := do(t, srv.Handler(), "GET", "/netstorage", "A", "")
	if _, present := w.Result().Header["X-Felhom-Agent-Version"]; present {
		t.Errorf("header must be absent when no version is configured, got %q", w.Header().Get("X-Felhom-Agent-Version"))
	}
}
