package hostruntime

import (
	"context"
	"reflect"
	"testing"

	"github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/permissionstatev1"
)

func TestAuthorizingSessionModeIsClosed(t *testing.T) {
	// The declared set, in order. The boundary values below are derived from it rather
	// than written as literals: a magic "first invalid" number silently stops testing the
	// boundary the moment a mode is added, which is exactly when it matters.
	modes := []AuthorizingSessionMode{
		AuthorizingSessionStrict,
		AuthorizingSessionRenewal,
		AuthorizingSessionControl,
		AuthorizingSessionBrowser,
	}
	for _, mode := range modes {
		if !mode.Valid() {
			t.Fatalf("mode %d is invalid", mode)
		}
	}

	if AuthorizingSessionMode(0).Valid() {
		t.Fatal("the zero value is a valid authorizing session mode, so an unset mode would admit")
	}
	if beyond := modes[len(modes)-1] + 1; beyond.Valid() {
		t.Fatalf("mode %d is valid but not declared", beyond)
	}
}

func TestLegacyAuthorizationInterfacesDoNotSatisfyStrongCapabilities(t *testing.T) {
	legacySession := reflect.TypeOf((*SessionAuthenticator)(nil)).Elem()
	strongSession := reflect.TypeOf((*AuthorizingSessionAdmitter)(nil)).Elem()
	if legacySession.Implements(strongSession) {
		t.Fatal("legacy SessionAuthenticator satisfies AuthorizingSessionAdmitter")
	}
	legacyPermissions := reflect.TypeOf((*PermissionProvider)(nil)).Elem()
	strongPermissions := reflect.TypeOf((*EffectivePermissionSnapshotProvider)(nil)).Elem()
	if legacyPermissions.Implements(strongPermissions) {
		t.Fatal("legacy PermissionProvider satisfies aggregate snapshot provider")
	}
}

func TestAuthorizingPermissionStateContextRejectsStaleSnapshot(t *testing.T) {
	lineageBytes := make([]byte, permissionstatev1.LineageBytes)
	lineageBytes[0] = 1
	lineage, err := permissionstatev1.LineageFromBytes(lineageBytes)
	if err != nil {
		t.Fatal(err)
	}
	snapshotVersion, _ := permissionstatev1.NewVersion(lineage, 1)
	floor, _ := permissionstatev1.NewVersion(lineage, 2)
	subject, _ := permissionstatev1.NewSubject("user-1", "profile-1")
	snapshot, _ := permissionstatev1.NewEffectiveSnapshot(snapshotVersion, []string{"ApiEnabled"}, nil)

	if _, err := ContextWithAuthorizingPermissionState(
		context.Background(),
		AuthorizingPermissionState{Subject: subject, Floor: floor, Snapshot: snapshot},
	); err == nil {
		t.Fatal("stale snapshot was installed")
	}
}
