package schema

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

// RelationshipFKColumn names a physical column that backs a non-system
// relationship (lookup / master-detail) field and must therefore be indexed.
type RelationshipFKColumn struct {
	Table  string
	Column string
}

// RelationshipFKColumns returns every non-system relationship FK column across
// the given table definitions. This is the single definition of "a relationship
// FK column that must be indexed" (#1407): every apply lane that materializes
// object definitions feeds its defs through here, so the rule is enforced
// identically regardless of how the columns were authored (pack spec, tenant
// overlay, admin CRUD). It is generic — a column qualifies purely from its
// shape (declares ReferenceTo targets) and never from an SObject name.
//
// Exclusions are structural, not name-based on business objects:
//   - Platform system columns (Id, OwnerId, CreatedById, RecordTypeId, ...) carry
//     no ReferenceTo in their ColumnDefinition (the reference *type* is assigned
//     only on the projected FieldMetadata), and are additionally guarded by
//     IsSystemField so a future system column that gains ReferenceTo stays out.
//   - Polymorphic discriminator columns carry no ReferenceTo.
//   - Metadata-only (ReadSource) objects own no physical table here; their
//     columns live in the read-source physical table, so they are skipped.
func RelationshipFKColumns(defs []TableDefinition) []RelationshipFKColumn {
	var out []RelationshipFKColumn
	for _, def := range defs {
		if def.ReadSource != nil {
			continue
		}
		for _, col := range def.Columns {
			if len(col.ReferenceTo) == 0 || constants.IsSystemField(col.Name) {
				continue
			}
			out = append(out, RelationshipFKColumn{Table: def.TableName, Column: col.Name})
		}
	}
	return out
}
