package uiapi

import "github.com/nexuscrm/backend/internal/features/metadata"

// --- Top Level Responses ---

// RecordUI represents the response for GET /ui-api/record-ui/{recordIds}
// It aggregates Records, Layouts, and ObjectInfos.
type RecordUI struct {
	Records     map[string]Record            `json:"records"`
	Layouts     map[string]map[string]Layout `json:"layouts"`
	ObjectInfos map[string]ObjectInfo        `json:"objectInfos"`
}

// --- Record Models ---

// RecordAccess represents record-level access rights for the current user.
// Matches Salesforce UI API v63.0 format.
type RecordAccess struct {
	HasReadAccess   bool `json:"hasReadAccess"`
	HasEditAccess   bool `json:"hasEditAccess"`
	HasDeleteAccess bool `json:"hasDeleteAccess"`
}

// Record represents a single record with decoded field values
type Record struct {
	ApiName          string                `json:"apiName"`
	Id               string                `json:"id"`
	Fields           map[string]FieldValue `json:"fields"`
	RecordAccess     *RecordAccess         `json:"recordAccess,omitempty"`
	ConversionState  *ConversionState      `json:"conversionState,omitempty"`
	LastModifiedDate string                `json:"lastModifiedDate,omitempty"`
	SystemModstamp   string                `json:"systemModstamp,omitempty"`
	RecordTypeId     string                `json:"recordTypeId,omitempty"`
}

// ConversionState represents a record's converted-state UI affordances.
// The shape is resolved by MetadataService from standard converted metadata,
// then populated from the FLS-filtered record image.
type ConversionState struct {
	IsConverted     bool             `json:"isConverted"`
	ConvertedDate   string           `json:"convertedDate,omitempty"`
	ConvertedByID   string           `json:"convertedById,omitempty"`
	ConvertedByName string           `json:"convertedByName,omitempty"`
	Links           []ConversionLink `json:"links,omitempty"`
}

// ConversionLink points to a record produced by a conversion-style action.
type ConversionLink struct {
	FieldName    string `json:"fieldName"`
	Label        string `json:"label"`
	TargetObject string `json:"targetObject"`
	RecordID     string `json:"recordId"`
}

// FieldValue represents a field's value and display value.
// Salesforce v63.0: displayValue is null for fields that need no formatting.
type FieldValue struct {
	DisplayValue *string     `json:"displayValue"` // null for non-formatted fields
	Value        interface{} `json:"value"`        // Raw value
}

// --- Object Info Models ---

// ObjectInfo represents metadata about an object
type ObjectInfo struct {
	ApiName             string                      `json:"apiName"`
	Label               string                      `json:"label"`
	LabelPlural         string                      `json:"labelPlural"`
	KeyPrefix           string                      `json:"keyPrefix"`
	ThemeInfo           *ThemeInfo                  `json:"themeInfo,omitempty"`
	Layoutable          bool                        `json:"layoutable"`
	Queryable           bool                        `json:"queryable"`
	Createable          bool                        `json:"createable"`
	Updateable          bool                        `json:"updateable"`
	Deletable           bool                        `json:"deletable"`
	Retrieveable        bool                        `json:"retrieveable"`
	Searchable          bool                        `json:"searchable"`
	Triggerable         bool                        `json:"triggerable"`
	Undeletable         bool                        `json:"undeletable"`
	Fields              map[string]FieldInfo        `json:"fields,omitempty"`
	DependentFields     map[string]interface{}      `json:"dependentFields,omitempty"`
	DefaultRecordTypeId string                      `json:"defaultRecordTypeId,omitempty"`
	RecordTypeInfos     map[string]UIRecordTypeInfo `json:"recordTypeInfos,omitempty"`
}

// UIRecordTypeInfo represents record type metadata in the UI API response
type UIRecordTypeInfo struct {
	Name                     string `json:"name"`
	RecordTypeId             string `json:"recordTypeId"`
	Available                bool   `json:"available"`
	DefaultRecordTypeMapping bool   `json:"defaultRecordTypeMapping"`
	Master                   bool   `json:"master"`
}

// FieldInfo represents metadata about a field
type FieldInfo struct {
	ApiName          string            `json:"apiName"`
	Label            string            `json:"label"`
	DataType         string            `json:"dataType"` // string, boolean, double, etc.
	Required         bool              `json:"required"`
	Createable       bool              `json:"createable"`
	Updateable       bool              `json:"updateable"`
	Length           int               `json:"length,omitempty"`
	Reference        bool              `json:"reference"`
	ReferenceToInfos []ReferenceToInfo `json:"referenceToInfos,omitempty"`
	RelationshipName string            `json:"relationshipName,omitempty"`
	NameField        bool              `json:"nameField"`
}

type ReferenceToInfo struct {
	ApiName    string   `json:"apiName"`
	NameFields []string `json:"nameFields"`
}

type ThemeInfo struct {
	Color   string `json:"color"`
	IconUrl string `json:"iconUrl"`
}

// --- Layout Models ---

// Layout represents a page layout for a specific mode (View, Edit, Create)
type Layout struct {
	Id            string            `json:"id"`
	LayoutName    string            `json:"layoutName,omitempty"`
	ObjectApiName string            `json:"objectApiName,omitempty"`
	LayoutType    string            `json:"layoutType,omitempty"`
	Mode          string            `json:"mode"` // View, Edit, Create
	Sections      []LayoutSection   `json:"sections"`
	CompactLayout []string          `json:"compactLayout,omitempty"`
	Tabs          []string          `json:"tabs,omitempty"`
	RelatedLists  []RelatedListInfo `json:"relatedLists"`
}

// RelatedListInfo describes a child relationship to render as a related list.
// Field names match the frontend RelatedListConfig type.
type RelatedListInfo struct {
	Id              string                          `json:"id"`
	Label           string                          `json:"label"`
	SecondaryLabel  string                          `json:"secondaryLabel,omitempty"`
	ObjectApiName   string                          `json:"objectApiName"`
	LookupField     string                          `json:"lookupField"`
	Fields          []string                        `json:"fields"`
	PrefillMappings map[string]string               `json:"prefillMappings,omitempty"`
	Resolution      *metadata.RelatedListResolution `json:"resolution,omitempty"`
}

type LayoutSection struct {
	Id          string            `json:"id"`
	Heading     string            `json:"heading"`
	Tab         string            `json:"tab,omitempty"`
	Columns     int               `json:"columns"`
	LayoutRows  []LayoutRow       `json:"layoutRows"`
	UseHeading  bool              `json:"useHeading"`
	Collapsible bool              `json:"collapsible"`
	IsCollapsed bool              `json:"isCollapsed"`
	FieldLabels map[string]string `json:"fieldLabels,omitempty"`
}

type LayoutRow struct {
	LayoutItems []LayoutItem `json:"layoutItems"`
}

type LayoutItem struct {
	Label             string            `json:"label"`
	LayoutComponents  []LayoutComponent `json:"layoutComponents"`
	Required          bool              `json:"required"`
	EditableForNew    bool              `json:"editableForNew"`
	EditableForUpdate bool              `json:"editableForUpdate"`
}

type LayoutComponent struct {
	ComponentType string                 `json:"componentType"`     // Field, Separator, etc.
	ApiName       string                 `json:"apiName,omitempty"` // For Field components
	Value         string                 `json:"value,omitempty"`
	Details       map[string]interface{} `json:"details,omitempty"` // Lookup expansion metadata
}

// --- Record Defaults Models (v63.0) ---

// RecordDefaults represents the response for GET /ui-api/record-defaults/create/:objectApiName
// and GET /ui-api/record-defaults/clone/:recordId
type RecordDefaults struct {
	ObjectApiName string             `json:"objectApiName"`
	RecordTypeId  string             `json:"recordTypeId,omitempty"`
	Record        RecordWithDefaults `json:"record"`
	ObjectInfo    *ObjectInfo        `json:"objectInfo,omitempty"`
}

// RecordWithDefaults represents a record with default field values
type RecordWithDefaults struct {
	ApiName string                `json:"apiName"`
	Fields  map[string]FieldValue `json:"fields"`
}

// --- List Info Models (v63.0) ---

// ListInfo represents the response for GET /ui-api/list-info/:objectApiName/:listViewApiName
type ListInfo struct {
	ApiName        string          `json:"apiName"`
	Id             string          `json:"id"`
	Label          string          `json:"label"`
	DeveloperName  string          `json:"developerName"`
	ObjectApiName  string          `json:"objectApiName"`
	Visibility     string          `json:"visibility"` // Public, Private, AllUsers
	DisplayColumns []DisplayColumn `json:"displayColumns,omitempty"`
	OrderedByInfo  []OrderInfo     `json:"orderedByInfo,omitempty"`
	FilterLogic    string          `json:"filterLogic,omitempty"`
}

// DisplayColumn represents a column in a list view
type DisplayColumn struct {
	FieldApiName string `json:"fieldApiName"`
	Label        string `json:"label"`
	Sortable     bool   `json:"sortable"`
}

// OrderInfo represents sort order for a list view
type OrderInfo struct {
	FieldApiName string `json:"fieldApiName"`
	IsAscending  bool   `json:"isAscending"`
}
