package health

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
)

// The env label is the machine-readable "is this prod?" signal (ENVIRONMENT.md):
// agents decide write-test safety from it, so it must always be present and
// mirror the header.
func TestLivenessReportsEnv(t *testing.T) {
	for _, env := range []string{"development", "production"} {
		req := httptest.NewRequest(http.MethodGet, "/health", nil)
		rec := httptest.NewRecorder()
		Liveness(env)(rec, req)
		if rec.Code != http.StatusOK {
			t.Fatalf("env %q: status = %d, want 200", env, rec.Code)
		}
		if got := rec.Header().Get("X-Environment"); got != env {
			t.Errorf("env %q: X-Environment = %q, want %q", env, got, env)
		}
		var body map[string]string
		if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
			t.Fatal(err)
		}
		if body["status"] != "ok" || body["env"] != env {
			t.Errorf("env %q: body = %v, want status ok + matching env", env, body)
		}
	}
}

func TestLivenessDefaultsUnknown(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/health", nil)
	rec := httptest.NewRecorder()
	Liveness("")(rec, req)
	var body map[string]string
	if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
		t.Fatal(err)
	}
	if body["env"] != "unknown" {
		t.Errorf("env = %q, want unknown (never imply production)", body["env"])
	}
}
