package schema

import (
	"time"

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

// ColumnDefinition represents a single column in a table
type ColumnDefinition struct {
	Name             string                 `json:"name"`
	Label            string                 `json:"label,omitempty"` // User-friendly label (defaults to Title Cased Name)
	Type             string                 `json:"type"`
	PhysicalName     string                 `json:"physicalName,omitempty"` // Explicit physical column name (e.g. `BacktickedName`)
	LogicalType      string                 `json:"logicalType,omitempty"`  // Optional: Override logical type (e.g. Password, Picklist)
	PrimaryKey       bool                   `json:"primaryKey,omitempty"`
	Unique           bool                   `json:"unique,omitempty"`
	Nullable         bool                   `json:"nullable,omitempty"`
	Default          string                 `json:"default,omitempty"`
	AutoIncrement    bool                   `json:"autoIncrement,omitempty"`
	ReferenceTo      []string               `json:"referenceTo,omitempty"`
	IsPolymorphic    bool                   `json:"isPolymorphic,omitempty"`
	Formula          string                 `json:"formula,omitempty"`
	ReturnType       string                 `json:"returnType,omitempty"`
	FormulaMode      string                 `json:"formulaMode,omitempty"` // "active" = Go engine, "frozen" = static, "" = GENERATED COLUMN (legacy)
	OnDelete         string                 `json:"onDelete,omitempty"`    // CASCADE, SET NULL, RESTRICT
	IsMasterDetail   bool                   `json:"isMasterDetail,omitempty"`
	RelationshipName string                 `json:"relationshipName,omitempty"`
	IsNameField      bool                   `json:"isNameField,omitempty"`
	Options          models.PicklistOptions `json:"options,omitempty"`
	Length           int                    `json:"length,omitempty"`
	// Source — provenance classifier propagated into FieldMetadata.Source on
	// column registration. Callers should set this to one of the
	// constants.FieldSource* values (see shared/pkg/constants/enums.go).
	// Empty value defers classification to BackfillSource at next startup
	// (DEFAULT constants.FieldSourceDiscovered). Issue #1582 RFC v1.5 PR A3.
	Source string `json:"source,omitempty"`
	// IsCompound — propagated into FieldMetadata.IsCompound. When set, ComposedFrom
	// should also be populated. Issue #1582 RFC v1.5 PR B (declaration parsing).
	IsCompound bool `json:"isCompound,omitempty"`
	// ComposedFrom — member field ApiNames for a compound parent. Issue #1582 RFC v1.5 PR B.
	ComposedFrom []string `json:"composedFrom,omitempty"`
}

// IndexDefinition represents an index on a table
type IndexDefinition struct {
	Name    string   `json:"name,omitempty"`
	Columns []string `json:"columns"`
	Unique  bool     `json:"unique,omitempty"`
}

// ForeignKeyDefinition represents a foreign key constraint
type ForeignKeyDefinition struct {
	Column     string `json:"column"`
	References string `json:"references"` // format: "tableName(columnName)"
	OnDelete   string `json:"onDelete,omitempty"`
	OnUpdate   string `json:"onUpdate,omitempty"`
}

// TableDefinition represents a complete table schema
type TableDefinition struct {
	TableName               string                     `json:"tableName"`
	TableType               string                     `json:"tableType"` // system_core, system_metadata, custom_object
	Category                string                     `json:"category"`  // auth, metadata, crm, etc.
	Label                   string                     `json:"label,omitempty"`
	Description             string                     `json:"description"`
	IsManaged               bool                       `json:"isManaged,omitempty"`
	SchemaVersion           string                     `json:"schemaVersion,omitempty"`
	SharingModel            string                     `json:"sharingModel,omitempty"`
	EnableHierarchySharing  bool                       `json:"enableHierarchySharing,omitempty"`
	RequiredWritePermission string                     `json:"requiredWritePermission,omitempty"`
	RequiredReadPermission  string                     `json:"requiredReadPermission,omitempty"`
	AccessPolicy            *models.ObjectAccessPolicy `json:"accessPolicy,omitempty"`
	DeleteMode              string                     `json:"deleteMode,omitempty"`
	Columns                 []ColumnDefinition         `json:"columns"`
	Indices                 []IndexDefinition          `json:"indices,omitempty"`
	ForeignKeys             []ForeignKeyDefinition     `json:"foreignKeys,omitempty"`
}

// FieldWithContext holds field metadata with context for batch operations
type FieldWithContext struct {
	Field            *models.FieldMetadata
	ColumnDefinition ColumnDefinition // Embed or reference column definition
	TableName        string
	ObjectID         string
	FieldID          string
}

// TableRegistryItem represents a table metadata entry
type TableRegistryItem struct {
	ID               string    `json:"id"`
	TableName        string    `json:"tableName"`
	TableType        string    `json:"tableType"`
	Category         string    `json:"category"`
	Description      string    `json:"description"`
	IsManaged        bool      `json:"isManaged"`
	SchemaVersion    string    `json:"schemaVersion"`
	CreatedBy        string    `json:"createdBy"`
	CreatedDate      time.Time `json:"createdDate"`
	LastModifiedDate time.Time `json:"lastModifiedDate"`
}
