package tenancy import ( "context" "encoding/json" "gorm.io/datatypes" ) type contextKey struct{} type Scope struct { TenantID uint64 TenantCode string TenantName string TenantStatus string Host string DomainType string ProfileJSON datatypes.JSON FeaturesJSON datatypes.JSON } func WithScope(ctx context.Context, scope Scope) context.Context { return context.WithValue(ctx, contextKey{}, scope) } func FromContext(ctx context.Context) (Scope, bool) { scope, ok := ctx.Value(contextKey{}).(Scope) return scope, ok && scope.TenantID > 0 } func MustFromContext(ctx context.Context) Scope { scope, ok := FromContext(ctx) if !ok { panic("tenant scope missing from context") } return scope } func (s Scope) Profile() map[string]any { return decodeJSONMap(s.ProfileJSON) } func (s Scope) Features() map[string]any { return decodeJSONMap(s.FeaturesJSON) } func decodeJSONMap(raw datatypes.JSON) map[string]any { if len(raw) == 0 { return map[string]any{} } var value map[string]any if err := json.Unmarshal(raw, &value); err != nil || value == nil { return map[string]any{} } return value }