package audit

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

	"github.com/gin-gonic/gin"
)

func init() { gin.SetMode(gin.TestMode) }

// runMiddleware drives the middleware against an optional header value and
// returns the AuditEntrypoint observed by the downstream handler's ctx.
func runMiddleware(t *testing.T, headerKey, headerVal string) AuditEntrypoint {
	t.Helper()
	r := gin.New()
	r.Use(AuditEntrypointMiddleware())
	var observed AuditEntrypoint
	r.GET("/probe", func(c *gin.Context) {
		observed = EntrypointFromContext(c.Request.Context())
		c.Status(http.StatusOK)
	})
	req := httptest.NewRequest(http.MethodGet, "/probe", nil)
	if headerKey != "" {
		req.Header.Set(headerKey, headerVal)
	}
	w := httptest.NewRecorder()
	r.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Fatalf("status: got %d, want 200", w.Code)
	}
	return observed
}

func TestAuditEntrypointMiddleware_DefaultsToRestAPI(t *testing.T) {
	got := runMiddleware(t, "", "")
	if got != EntrypointRestAPI {
		t.Fatalf("default: got %q, want %q", got, EntrypointRestAPI)
	}
}

func TestAuditEntrypointMiddleware_BulkHeaderFlipsToBulk(t *testing.T) {
	cases := []string{"true", "TRUE", "True", "1", "yes", "YES"}
	for _, v := range cases {
		got := runMiddleware(t, HeaderBulkAPI, v)
		if got != EntrypointBulkAPI {
			t.Errorf("bulk header %q: got %q, want %q", v, got, EntrypointBulkAPI)
		}
	}
}

func TestAuditEntrypointMiddleware_NonTruthyHeaderStaysRest(t *testing.T) {
	cases := []string{"", "false", "no", "0", "   "}
	for _, v := range cases {
		got := runMiddleware(t, HeaderBulkAPI, v)
		if got != EntrypointRestAPI {
			t.Errorf("non-truthy header %q: got %q, want %q", v, got, EntrypointRestAPI)
		}
	}
}
