package runtimeconfig

import (
	"encoding/json"
	"os"
	"path/filepath"
	"testing"
)

func TestUserAPICallerConfigSeparatesAuthenticatedClientFromOwners(t *testing.T) {
	base := `{"schema":"nexuscrm.runtime-api-serving/v4","permission_state_protocol":"permission_state.v1","replica_id":"replica-a","authorized_workload_ids":["client-a","handler-a"],"user_api_callers":["client-a"],"org_id":"org-a","app_installation_id":"app-a","catalog_snapshot_store_root":"/var/lib/catalog","expected_service_release_digest":"sha256:service","schema_generation":1,"engine_generation":1,"identity_attempt_cap":"2s","session_scope_capabilities":{"api":["runtime.records.query.v1"]},"capabilities":[{"app_capability_id":"app.query","runtime_capability_id":"runtime.records.query.v1","authorized_workload_id":"handler-a","expected_ownership_epoch":1,"expected_compatibility_receipt_digest":"sha256:receipt","admission_lease":"3s"}]}`
	for _, tc := range []struct {
		name    string
		callers []string
		ok      bool
	}{{"registered", []string{"client-a"}, true}, {"absent", nil, true}, {"unregistered", []string{"other"}, false}, {"handler", []string{"handler-a"}, false}, {"duplicate", []string{"client-a", "client-a"}, false}, {"noncanonical", []string{" client-a"}, false}} {
		t.Run(tc.name, func(t *testing.T) {
			var d map[string]any
			if err := json.Unmarshal([]byte(base), &d); err != nil {
				t.Fatal(err)
			}
			d["user_api_callers"] = tc.callers
			raw, _ := json.Marshal(d)
			p := filepath.Join(t.TempDir(), "serving.json")
			if err := os.WriteFile(p, raw, 0600); err != nil {
				t.Fatal(err)
			}
			_, err := loadServingConfig(p)
			if (err == nil) != tc.ok {
				t.Fatalf("ok=%v err=%v", tc.ok, err)
			}
		})
	}
}
