package hub

import (
	"context"
	"errors"
	"net/http"
	"strings"
	"testing"
)

const testBearer = "super-secret-bearer-key"

func TestClient_SetsBearerAndParsesEnvelope(t *testing.T) {
	var gotAuth, gotCT, gotPath, gotMethod string
	c := testClient(func(r *http.Request) (*http.Response, error) {
		gotAuth = r.Header.Get("Authorization")
		gotCT = r.Header.Get("Content-Type")
		gotPath = r.URL.Path
		gotMethod = r.Method
		return httpResp(200, `{"status":"ok","poll_interval_seconds":900}`), nil
	})
	env, err := c.Report(context.Background(), &HostReport{HostID: "h"})
	if err != nil {
		t.Fatalf("Report: %v", err)
	}
	if gotAuth != "Bearer "+testBearer {
		t.Errorf("auth header = %q", gotAuth)
	}
	if gotCT != "application/json" {
		t.Errorf("content-type = %q", gotCT)
	}
	if gotMethod != http.MethodPost || gotPath != reportPath {
		t.Errorf("method/path = %s %s", gotMethod, gotPath)
	}
	if env.PollIntervalSeconds == nil || *env.PollIntervalSeconds != 900 {
		t.Errorf("envelope poll = %v", env.PollIntervalSeconds)
	}
}

func TestClient_Non2xxTypedErrorRedactsToken(t *testing.T) {
	c := testClient(func(r *http.Request) (*http.Response, error) {
		return httpResp(503, "service unavailable"), nil
	})
	_, err := c.Report(context.Background(), &HostReport{HostID: "h"})
	var he *HTTPError
	if !errors.As(err, &he) {
		t.Fatalf("want *HTTPError, got %T: %v", err, err)
	}
	if he.StatusCode != 503 {
		t.Errorf("status = %d", he.StatusCode)
	}
	if strings.Contains(err.Error(), testBearer) {
		t.Fatalf("bearer token leaked into error: %q", err.Error())
	}
}

func TestClient_TransportErrorTypedRedactsToken(t *testing.T) {
	c := testClient(func(r *http.Request) (*http.Response, error) {
		return nil, errors.New("dial tcp: connection refused")
	})
	_, err := c.Report(context.Background(), &HostReport{HostID: "h"})
	var te *TransportError
	if !errors.As(err, &te) {
		t.Fatalf("want *TransportError, got %T: %v", err, err)
	}
	if strings.Contains(err.Error(), testBearer) {
		t.Fatalf("bearer token leaked into error: %q", err.Error())
	}
}
