package auth

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

// Regression (multi-tenant §5.4): ScopeMiddleware passed as an extra to
// Middleware must run AFTER authentication, so the loader sees the user and
// the handler sees a restricted scope. A previous composition bug ran the
// extras BEFORE authentication; UserFrom was nil there and every caller
// silently became platform-wide.
func TestMiddlewareRunsExtrasAfterAuthentication(t *testing.T) {	loaderCalled := false
	sm := ScopeMiddleware(func(ctx context.Context, userID int64) ([]int64, error) {
		loaderCalled = true
		if userID != 5 {
			t.Fatalf("loader got userID %d, want 5", userID)
		}
		return []int64{4}, nil
	})

	var inner http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sc := StoreScopeFrom(r.Context())
		if sc.PlatformWide() {
			t.Fatal("handler saw platform-wide scope for a scoped user")
		}
		if !sc.AllowsID(4) || sc.AllowsID(1) {
			t.Fatalf("scope ids wrong: %v", sc.IDs())
		}
		w.WriteHeader(200)
	})
	h := sm(inner)

	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req = req.WithContext(ToContext(req.Context(), &User{ID: 5}, 1))
	h.ServeHTTP(httptest.NewRecorder(), req)

	if !loaderCalled {
		t.Fatal("scope loader was not called")
	}
}

// Full-stack shape: Middleware(svc, ScopeMiddleware(load)) — the stub service
// path needs a DB-backed repository, so it lives in the integration suite.
func TestMiddlewareScopeEndToEnd(t *testing.T) {
	t.Skip("requires DB-backed repository; covered by integration suite")
}

// silence unused import when json tag trimming changes
var _ = json.Marshal
