package permissions

import (
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/models"
)

// ProjectPermissionGrantsOntoRecord mutates `record` in place, setting a
// bool value for every SystemPermission virtual field declared on
// schema (as produced by the SchemaDecorator). `grants` is the junction
// state for this PermissionSet keyed by catalog APIName; missing
// entries default to false.
//
// Schema-driven, not catalog-driven: using the decorated schema is
// symmetric with the describe handler (which emits the same set of
// virtual fields) and lets the caller avoid a second catalog read.
// Safe to call on a record whose shape is already SF-correct —
// existing keys under the virtual field APIName are overwritten by
// the junction truth. A schema with no SystemPermission virtuals (the
// common case: every object other than PermissionSet) is a no-op.
func ProjectPermissionGrantsOntoRecord(record models.SObject, schema *models.ObjectMetadata, grants map[string]bool) {
	ProjectPermissionGrantFieldsOntoRecord(record, models.VirtualFieldsByKind(schema, constants.VirtualFieldSystemPermission), grants)
}

// ProjectPermissionGrantFieldsOntoRecord mutates `record` in place, setting a
// bool value only for the supplied SystemPermission virtual fields. Query paths
// use this to preserve an explicit SELECT shape; retrieve / wildcard paths pass
// the full schema-owned field set through ProjectPermissionGrantsOntoRecord.
func ProjectPermissionGrantFieldsOntoRecord(record models.SObject, fields []models.FieldMetadata, grants map[string]bool) {
	for _, f := range fields {
		if !f.IsVirtual || f.VirtualKind != constants.VirtualFieldSystemPermission {
			continue
		}
		record[f.APIName] = grants[f.VirtualSourceAPIName]
	}
}
