package httputil_test

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

	"kjol/httputil"
)

func TestCorsMiddleware_SetsBundleVersionOnAPI(t *testing.T) {
	const testVersion = "test-bundle-version"

	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/ping", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	handler := httputil.CorsMiddleware(httputil.CorsConfig{
		BundleVersion: func() string { return testVersion },
	})(mux)

	t.Run("api route", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/api/ping", nil)
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, req)

		if got := rec.Header().Get("X-Bundle-Version"); got != testVersion {
			t.Fatalf("expected X-Bundle-Version %q, got %q", testVersion, got)
		}
	})

	t.Run("non-api route", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/health", nil)
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, req)

		if got := rec.Header().Get("X-Bundle-Version"); got != "" {
			t.Fatalf("expected no bundle header on non-API route, got %q", got)
		}
	})
}
