//go:build crm

package crm

import (
	"context"
	"testing"

	"github.com/nexuscrm/shared/pkg/constants"
)

func TestScimConfigCacheReadsOnlyL2SingletonAndFailsClosedWhenMissing(t *testing.T) {
	cfg := testScimConfig()
	q := testConfigQuery(cfg)
	cc := newScimConfigCache()

	if err := cc.refresh(context.Background(), q, testSession(), true); err != nil {
		t.Fatalf("refresh L2 singleton: %v", err)
	}
	if got := cc.current(); !scimConfigServeable(got) || got.serviceUsername != cfg.serviceUsername {
		t.Fatalf("L2 record did not become the effective configuration: %+v", got)
	}
	if q.lastSpec.ObjectAPIName != scimConfigObject || q.lastSpec.Limit != 1 {
		t.Fatalf("wrong config read spec: %+v", q.lastSpec)
	}
	if constants.GetSecurityContext(q.lastCtx) != constants.SystemContext {
		t.Fatalf("config read security context = %v, want system", constants.GetSecurityContext(q.lastCtx))
	}

	delete(q.configRecords.byField[scimFieldName], scimConfigSingletonName)
	if err := cc.refresh(context.Background(), q, testSession(), true); err != nil {
		t.Fatalf("missing singleton read must be a successful empty result, got %v", err)
	}
	if scimConfigServeable(cc.current()) {
		t.Fatalf("a missing L2 singleton must fail closed, got %+v", cc.current())
	}
}

func TestScimConfigFromRecordDoesNotDefaultRequiredL2Values(t *testing.T) {
	cfg := scimConfigFromRecord(testConfigRecord(scimIdentityConfig{}))
	if scimConfigServeable(cfg) {
		t.Fatalf("blank L2 record must not become serveable through defaults: %+v", cfg)
	}
}
