package middleware

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

	"haixun-backend/internal/config"
	"haixun-backend/internal/library/authctx"
)

func TestMemberAuth_DevHeaderFallback(t *testing.T) {
	called := false
	handler := MemberAuth(nil, config.AuthConf{DevHeaderFallback: true}, func(w http.ResponseWriter, r *http.Request) {
		called = true
		actor, ok := authctx.ActorFromContext(r.Context())
		if !ok || actor.UID != "u1" {
			t.Fatalf("actor = %+v, ok=%v", actor, ok)
		}
	})

	req := httptest.NewRequest(http.MethodPost, "/api/v1/ai/chat", nil)
	req.Header.Set("X-Tenant-ID", "default")
	req.Header.Set("X-UID", "u1")
	req.Header.Set("Authorization", "Bearer sk-provider-key")
	rec := httptest.NewRecorder()
	handler(rec, req)

	if !called {
		t.Fatal("expected handler to be called via dev headers")
	}
}

func TestAuth_RequiresAuthorizationBearer(t *testing.T) {
	handler := Auth(nil, config.AuthConf{DevHeaderFallback: false}, func(w http.ResponseWriter, r *http.Request) {
		t.Fatal("handler should not be called")
	})

	req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs", nil)
	rec := httptest.NewRecorder()
	handler(rec, req)

	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("status = %d, want 401", rec.Code)
	}
}
