package main

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/kami/maven/internal/config"
)

// TestWireEcosystem_HexisToken — a configured Hexis token reaches the wire.
//
// This is the regression that closes the 2026-08-01 re-vendor. The copy of
// github.com/kami/hexis checked into vendor/ used to predate Client.WithToken,
// so a configured token could not be sent at all; wireEcosystem refused to wire
// Hexis rather than execute unauthenticated. Both halves of that are gone. The
// test asserts the outcome the refusal was standing in for: the header goes
// out, so nobody has to trust a boot log to know auth is on.
func TestWireEcosystem_HexisToken(t *testing.T) {
	var gotAuth string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotAuth = r.Header.Get("Authorization")
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`[]`))
	}))
	defer srv.Close()

	cfg := &config.Config{Hexis: &config.HexisConfig{URL: srv.URL, Token: "s3cret"}}
	w := wireEcosystem(cfg)
	if w.hexis == nil {
		t.Fatal("hexis not wired with a token configured")
	}
	if _, err := w.discoverCapabilities(context.Background(), "entity-1"); err != nil {
		t.Fatalf("discoverCapabilities: %v", err)
	}
	if want := "Bearer s3cret"; gotAuth != want {
		t.Errorf("Authorization = %q; want %q", gotAuth, want)
	}
}

// TestWireEcosystem_HexisNoToken — no token configured still wires, unauthed.
// Hexis without auth is a valid deployment on a trusted box, and the re-vendor
// must not have turned the token into a requirement.
func TestWireEcosystem_HexisNoToken(t *testing.T) {
	var sawAuth bool
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sawAuth = r.Header.Get("Authorization") != ""
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`[]`))
	}))
	defer srv.Close()

	cfg := &config.Config{Hexis: &config.HexisConfig{URL: srv.URL}}
	w := wireEcosystem(cfg)
	if w.hexis == nil {
		t.Fatal("hexis not wired without a token")
	}
	if _, err := w.discoverCapabilities(context.Background(), "entity-1"); err != nil {
		t.Fatalf("discoverCapabilities: %v", err)
	}
	if sawAuth {
		t.Error("Authorization header sent with no token configured")
	}
}
