package ratelimit

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

	"github.com/pingcap/agent-git-service/internal/tenant"
)

func TestSubjectForRequest_TreatsEmbeddedActorsAsAuthenticated(t *testing.T) {
	t.Parallel()

	req := httptest.NewRequest("GET", "/api/v3/user", nil)
	req = req.WithContext(WithActor(req.Context(), "embedded:meshx:subject-1"))

	subject := SubjectForRequest(req)
	if !subject.Authenticated {
		t.Fatal("expected embedded actor to be treated as authenticated")
	}
	if got := subject.Actor; got != "embedded:meshx:subject-1" {
		t.Fatalf("actor: got %q want %q", got, "embedded:meshx:subject-1")
	}
}

func TestSubjectForRequestScopesSameActorByTenant(t *testing.T) {
	t.Parallel()

	request := func(id tenant.ID) Subject {
		req := httptest.NewRequest("GET", "/api/v3/user", nil)
		ctx := tenant.WithInfo(req.Context(), tenant.Info{
			ID:               id,
			CanonicalBaseURL: "https://" + string(id) + ".example.test",
		})
		ctx = WithActor(ctx, "token:same")
		return SubjectForRequest(req.WithContext(ctx))
	}

	a := request("tenant-a")
	b := request("tenant-b")
	if a.Actor == b.Actor {
		t.Fatalf("same actor shared a tenant-independent key %q", a.Actor)
	}
	if !a.Authenticated || !b.Authenticated {
		t.Fatal("tenant scoping changed authenticated actor classification")
	}
}
