package roles

import (
	"time"

	"chorus.services/bzzz/pkg/security"
	"chorus.services/bzzz/pkg/ucxl"
	slurpContext "chorus.services/bzzz/pkg/slurp/context"
)

// Stub types for interfaces (to be implemented later)
type RoleFilter struct {
	RoleIDs     []string `json:"role_ids,omitempty"`
	Permissions []string `json:"permissions,omitempty"`
}

type RoleHierarchy struct {
	Roles map[string][]string `json:"roles"`
}

type RoleValidation struct {
	Valid   bool     `json:"valid"`
	Errors  []string `json:"errors"`
}

type RoleStatistics struct {
	TotalRoles int `json:"total_roles"`
	ActiveRoles int `json:"active_roles"`
}

type AccessStatistics struct {
	TotalRequests int `json:"total_requests"`
	GrantedRequests int `json:"granted_requests"`
}

type FilteringStatistics struct {
	TotalFiltered int `json:"total_filtered"`
	PassedFilter int `json:"passed_filter"`
}

type EvaluationStatistics struct {
	TotalEvaluations int `json:"total_evaluations"`
	SuccessfulEvaluations int `json:"successful_evaluations"`
}

type PermissionChange struct {
	RoleID string `json:"role_id"`
	Permission string `json:"permission"`
	Action string `json:"action"`
	Timestamp time.Time `json:"timestamp"`
}

type SecurityEvent struct {
	EventType string `json:"event_type"`
	RoleID string `json:"role_id"`
	Timestamp time.Time `json:"timestamp"`
	Details map[string]interface{} `json:"details"`
}

type AuditFilter struct {
	RoleIDs []string `json:"role_ids,omitempty"`
	EventTypes []string `json:"event_types,omitempty"`
	StartTime *time.Time `json:"start_time,omitempty"`
	EndTime *time.Time `json:"end_time,omitempty"`
}

type AuditEntry struct {
	ID string `json:"id"`
	Timestamp time.Time `json:"timestamp"`
	EventType string `json:"event_type"`
	RoleID string `json:"role_id"`
	Details map[string]interface{} `json:"details"`
}

type AuditStatistics struct {
	TotalEntries int `json:"total_entries"`
	RecentEntries int `json:"recent_entries"`
}

type RetentionPolicy struct {
	Duration time.Duration `json:"duration"`
	MaxEntries int `json:"max_entries"`
}

type ArchiveResult struct {
	ArchivedCount int `json:"archived_count"`
	Success bool `json:"success"`
}

type EncryptionStatistics struct {
	TotalEncrypted int `json:"total_encrypted"`
	EncryptionErrors int `json:"encryption_errors"`
}

type AccessPolicy struct {
	ID string `json:"id"`
	Name string `json:"name"`
	Rules []string `json:"rules"`
	CreatedAt time.Time `json:"created_at"`
}

type PolicyFilter struct {
	PolicyIDs []string `json:"policy_ids,omitempty"`
	Names []string `json:"names,omitempty"`
}

type AccessRequest struct {
	ID string `json:"id"`
	UserID string `json:"user_id"`
	RoleID string `json:"role_id"`
	Resource string `json:"resource"`
	Action string `json:"action"`
	Timestamp time.Time `json:"timestamp"`
}

type PolicyEvaluation struct {
	PolicyID string `json:"policy_id"`
	Result bool `json:"result"`
	Reason string `json:"reason"`
	Timestamp time.Time `json:"timestamp"`
}

type PolicyValidation struct {
	Valid bool `json:"valid"`
	Errors []string `json:"errors"`
	Warnings []string `json:"warnings"`
}

type UserSession struct {
	ID string `json:"id"`
	UserID string `json:"user_id"`
	RoleIDs []string `json:"role_ids"`
	CreatedAt time.Time `json:"created_at"`
	LastAccessed time.Time `json:"last_accessed"`
	ExpiresAt time.Time `json:"expires_at"`
	Active bool `json:"active"`
}

type SessionUpdate struct {
	SessionID string `json:"session_id"`
	RoleIDs []string `json:"role_ids,omitempty"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	Active *bool `json:"active,omitempty"`
}

type CleanupResult struct {
	CleanedSessions int `json:"cleaned_sessions"`
	Success bool `json:"success"`
}

type SessionStatistics struct {
	ActiveSessions int `json:"active_sessions"`
	TotalSessions int `json:"total_sessions"`
	ExpiredSessions int `json:"expired_sessions"`
}

type Delegation struct {
	ID string `json:"id"`
	DelegatorID string `json:"delegator_id"`
	DelegateID string `json:"delegate_id"`
	RoleID string `json:"role_id"`
	CreatedAt time.Time `json:"created_at"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	Active bool `json:"active"`
}

type DelegationValidation struct {
	Valid bool `json:"valid"`
	Errors []string `json:"errors"`
	Warnings []string `json:"warnings"`
}

type DelegationStatistics struct {
	ActiveDelegations int `json:"active_delegations"`
	TotalDelegations int `json:"total_delegations"`
	ExpiredDelegations int `json:"expired_delegations"`
}

// Permission represents a specific permission within the system
type Permission string

const (
	// Context permissions
	PermissionReadContext      Permission = "read_context"       // Read context data
	PermissionWriteContext     Permission = "write_context"      // Write/modify context data
	PermissionDeleteContext    Permission = "delete_context"     // Delete context data
	PermissionCreateContext    Permission = "create_context"     // Create new context
	PermissionViewSensitive    Permission = "view_sensitive"     // View sensitive context data
	
	// Code-related permissions
	PermissionReadCode         Permission = "read_code"          // Read source code
	PermissionWriteCode        Permission = "write_code"         // Write/modify source code
	PermissionDeleteCode       Permission = "delete_code"        // Delete source code
	PermissionExecuteCode      Permission = "execute_code"       // Execute code
	PermissionDeployCode       Permission = "deploy_code"        // Deploy code changes
	
	// Architecture permissions
	PermissionViewArchitecture Permission = "view_architecture"  // View architectural information
	PermissionModifyArchitecture Permission = "modify_architecture" // Modify architectural decisions
	PermissionCreateArchitecture Permission = "create_architecture" // Create architectural components
	
	// Administrative permissions
	PermissionManageRoles      Permission = "manage_roles"       // Manage roles and permissions
	PermissionManageUsers      Permission = "manage_users"       // Manage user assignments
	PermissionViewAuditLog     Permission = "view_audit_log"     // View audit logs
	PermissionSystemConfig     Permission = "system_config"     // Configure system settings
	
	// Intelligence permissions
	PermissionGenerateContext  Permission = "generate_context"   // Generate new context
	PermissionAnalyzePatterns  Permission = "analyze_patterns"   // Analyze code patterns
	PermissionViewMetrics      Permission = "view_metrics"       // View system metrics
	
	// Temporal permissions
	PermissionViewHistory      Permission = "view_history"       // View context history
	PermissionModifyHistory    Permission = "modify_history"     // Modify historical data
	PermissionViewDecisions    Permission = "view_decisions"     // View decision information
	
	// Goal alignment permissions
	PermissionViewGoals        Permission = "view_goals"         // View project goals
	PermissionModifyGoals      Permission = "modify_goals"       // Modify project goals
	PermissionViewAlignment    Permission = "view_alignment"     // View alignment scores
	
	// Distribution permissions
	PermissionDistributeContext Permission = "distribute_context" // Distribute context via DHT
	PermissionManageReplicas   Permission = "manage_replicas"    // Manage context replicas
	PermissionViewClusterInfo  Permission = "view_cluster_info"  // View cluster information
)

// AccessType represents different types of access to context
type AccessType string

const (
	AccessTypeRead     AccessType = "read"     // Read-only access
	AccessTypeWrite    AccessType = "write"    // Write/modify access
	AccessTypeDelete   AccessType = "delete"   // Delete access
	AccessTypeExecute  AccessType = "execute"  // Execute access
	AccessTypeAdmin    AccessType = "admin"    // Administrative access
)

// Role represents a role with associated permissions and metadata
type Role struct {
	ID              string                 `json:"id"`               // Unique role identifier
	Name            string                 `json:"name"`             // Human-readable role name
	Description     string                 `json:"description"`      // Role description
	Permissions     []Permission           `json:"permissions"`      // Granted permissions
	AccessLevel     security.AccessLevel     `json:"access_level"`     // Maximum access level
	Priority        int                    `json:"priority"`         // Role priority for conflicts
	
	// Hierarchy
	ParentRoleID    *string                `json:"parent_role_id,omitempty"` // Parent role
	ChildRoleIDs    []string               `json:"child_role_ids"`   // Child roles
	InheritsFrom    []string               `json:"inherits_from"`    // Roles to inherit from
	
	// Constraints
	MaxUsers        *int                   `json:"max_users,omitempty"`      // Maximum users with role
	RequiresMFA     bool                   `json:"requires_mfa"`     // Requires multi-factor auth
	SessionTimeout  *time.Duration         `json:"session_timeout,omitempty"` // Session timeout
	IPRestrictions  []string               `json:"ip_restrictions"`  // IP address restrictions
	TimeRestrictions *TimeRestrictions     `json:"time_restrictions,omitempty"` // Time-based restrictions
	
	// Status and lifecycle
	Status          RoleStatus             `json:"status"`           // Current status
	CreatedAt       time.Time              `json:"created_at"`       // When created
	UpdatedAt       time.Time              `json:"updated_at"`       // When last updated
	CreatedBy       string                 `json:"created_by"`       // Who created it
	ExpiresAt       *time.Time             `json:"expires_at,omitempty"` // When role expires
	
	// Metadata
	Tags            []string               `json:"tags"`             // Role tags
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// RoleStatus represents the status of a role
type RoleStatus string

const (
	RoleStatusActive     RoleStatus = "active"      // Role is active
	RoleStatusInactive   RoleStatus = "inactive"    // Role is inactive
	RoleStatusDeprecated RoleStatus = "deprecated"  // Role is deprecated
	RoleStatusExpired    RoleStatus = "expired"     // Role has expired
)

// TimeRestrictions represents time-based access restrictions
type TimeRestrictions struct {
	AllowedHours    []int                  `json:"allowed_hours"`     // Hours when access allowed (0-23)
	AllowedDays     []time.Weekday         `json:"allowed_days"`      // Days when access allowed
	Timezone        string                 `json:"timezone"`          // Timezone for restrictions
	ValidFrom       *time.Time             `json:"valid_from,omitempty"`   // Valid from date
	ValidUntil      *time.Time             `json:"valid_until,omitempty"`  // Valid until date
	ExceptionWindows []*TimeWindow         `json:"exception_windows"` // Exception time windows
}

// TimeWindow represents a time window for permissions or restrictions
type TimeWindow struct {
	StartTime       time.Time              `json:"start_time"`        // Window start time
	EndTime         time.Time              `json:"end_time"`          // Window end time
	Timezone        string                 `json:"timezone"`          // Window timezone
	Recurring       bool                   `json:"recurring"`         // Whether window recurs
	RecurrenceRule  string                 `json:"recurrence_rule"`   // Recurrence rule (cron-like)
}

// RoleAssignment represents assignment of a role to a user
type RoleAssignment struct {
	ID              string                 `json:"id"`               // Assignment ID
	UserID          string                 `json:"user_id"`          // User identifier
	RoleID          string                 `json:"role_id"`          // Role identifier
	AssignedBy      string                 `json:"assigned_by"`      // Who assigned the role
	AssignedAt      time.Time              `json:"assigned_at"`      // When assigned
	ExpiresAt       *time.Time             `json:"expires_at,omitempty"` // When assignment expires
	Conditions      []*AssignmentCondition `json:"conditions"`       // Assignment conditions
	Status          AssignmentStatus       `json:"status"`           // Assignment status
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// AssignmentCondition represents a condition for role assignment
type AssignmentCondition struct {
	Type            ConditionType          `json:"type"`             // Condition type
	Expression      string                 `json:"expression"`       // Condition expression
	Parameters      map[string]interface{} `json:"parameters"`       // Condition parameters
	Description     string                 `json:"description"`      // Condition description
}

// ConditionType represents types of assignment conditions
type ConditionType string

const (
	ConditionTypeTime        ConditionType = "time"         // Time-based condition
	ConditionTypeLocation    ConditionType = "location"     // Location-based condition
	ConditionTypeResource    ConditionType = "resource"     // Resource-based condition
	ConditionTypeContext     ConditionType = "context"      // Context-based condition
	ConditionTypeGroup       ConditionType = "group"        // Group membership condition
)

// AssignmentStatus represents status of role assignment
type AssignmentStatus string

const (
	AssignmentStatusActive    AssignmentStatus = "active"     // Assignment is active
	AssignmentStatusInactive  AssignmentStatus = "inactive"   // Assignment is inactive
	AssignmentStatusExpired   AssignmentStatus = "expired"    // Assignment has expired
	AssignmentStatusRevoked   AssignmentStatus = "revoked"    // Assignment was revoked
	AssignmentStatusPending   AssignmentStatus = "pending"    // Assignment is pending approval
)

// ContextPermissions represents permissions for a specific context
type ContextPermissions struct {
	Address         ucxl.Address           `json:"address"`          // Context address
	UserID          string                 `json:"user_id"`          // User identifier
	CanRead         bool                   `json:"can_read"`         // Can read context
	CanWrite        bool                   `json:"can_write"`        // Can write/modify context
	CanDelete       bool                   `json:"can_delete"`       // Can delete context
	CanDistribute   bool                   `json:"can_distribute"`   // Can distribute context
	AccessLevel     security.AccessLevel     `json:"access_level"`     // Granted access level
	AllowedFields   []string               `json:"allowed_fields"`   // Fields user can access
	RestrictedFields []string              `json:"restricted_fields"` // Fields user cannot access
	Conditions      []*PermissionCondition `json:"conditions"`       // Access conditions
	EvaluatedAt     time.Time              `json:"evaluated_at"`     // When evaluated
	ExpiresAt       *time.Time             `json:"expires_at,omitempty"` // When expires
}

// PermissionCondition represents a condition for permission grant
type PermissionCondition struct {
	Type            ConditionType          `json:"type"`             // Condition type
	Expression      string                 `json:"expression"`       // Condition expression
	Satisfied       bool                   `json:"satisfied"`        // Whether condition is satisfied
	EvaluatedAt     time.Time              `json:"evaluated_at"`     // When condition was evaluated
	Message         string                 `json:"message"`          // Condition evaluation message
}

// AccessToken represents a time-limited access token
type AccessToken struct {
	Token           string                 `json:"token"`            // Token string
	UserID          string                 `json:"user_id"`          // User identifier
	Permissions     []Permission           `json:"permissions"`      // Granted permissions
	AccessLevel     security.AccessLevel     `json:"access_level"`     // Granted access level
	IssuedAt        time.Time              `json:"issued_at"`        // When issued
	ExpiresAt       time.Time              `json:"expires_at"`       // When expires
	Scope           []string               `json:"scope"`            // Token scope
	RefreshToken    *string                `json:"refresh_token,omitempty"` // Refresh token
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// TokenValidation represents result of token validation
type TokenValidation struct {
	Valid           bool                   `json:"valid"`            // Whether token is valid
	Token           *AccessToken           `json:"token,omitempty"`  // Token details if valid
	ErrorCode       string                 `json:"error_code,omitempty"` // Error code if invalid
	ErrorMessage    string                 `json:"error_message,omitempty"` // Error message if invalid
	ValidatedAt     time.Time              `json:"validated_at"`     // When validation occurred
}

// AccessDecision represents an access control decision
type AccessDecision struct {
	ID              string                 `json:"id"`               // Decision ID
	UserID          string                 `json:"user_id"`          // User identifier
	Resource        string                 `json:"resource"`         // Accessed resource
	Action          string                 `json:"action"`           // Attempted action
	Permission      Permission             `json:"permission"`       // Required permission
	Decision        DecisionResult         `json:"decision"`         // Access decision
	Reason          string                 `json:"reason"`           // Decision reason
	EvaluatedPolicies []string             `json:"evaluated_policies"` // Policies evaluated
	EvaluationTime  time.Duration          `json:"evaluation_time"`  // Time taken to evaluate
	DecidedAt       time.Time              `json:"decided_at"`       // When decision was made
	Context         map[string]interface{} `json:"context"`          // Decision context
}

// DecisionResult represents the result of an access decision
type DecisionResult string

const (
	DecisionAllow   DecisionResult = "allow"    // Access allowed
	DecisionDeny    DecisionResult = "deny"     // Access denied
	DecisionTimeout DecisionResult = "timeout"  // Decision timed out
	DecisionError   DecisionResult = "error"    // Decision error
)

// LabeledContext represents context with security labels applied
type LabeledContext struct {
	Context         *slurpContext.ContextNode `json:"context"`         // Original context
	SecurityLabels  []*SecurityLabel         `json:"security_labels"` // Applied security labels
	ClassificationLevel string               `json:"classification_level"` // Overall classification
	RequiredClearance security.AccessLevel     `json:"required_clearance"` // Required clearance level
	LabeledAt       time.Time                `json:"labeled_at"`      // When labels were applied
	LabeledBy       string                   `json:"labeled_by"`      // Who/what applied labels
}

// SecurityLabel represents a security label applied to context
type SecurityLabel struct {
	Type            LabelType              `json:"type"`             // Label type
	Value           string                 `json:"value"`            // Label value
	Confidence      float64                `json:"confidence"`       // Labeling confidence
	AppliedReason   string                 `json:"applied_reason"`   // Why label was applied
	RequiredLevel   security.AccessLevel     `json:"required_level"`   // Required access level
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// LabelType represents types of security labels
type LabelType string

const (
	LabelTypeClassification LabelType = "classification" // Classification label
	LabelTypeCategory       LabelType = "category"       // Category label
	LabelTypeSensitivity    LabelType = "sensitivity"    // Sensitivity label
	LabelTypeHandling       LabelType = "handling"       // Handling instruction
	LabelTypeProject        LabelType = "project"        // Project-specific label
	LabelTypeCustom         LabelType = "custom"         // Custom label
)

// RoleContextView represents a role-specific view of context
type RoleContextView struct {
	OriginalContext *slurpContext.ContextNode `json:"original_context"`  // Original context
	FilteredContext *slurpContext.ContextNode `json:"filtered_context"`  // Role-filtered context
	RoleID          string                   `json:"role_id"`           // Role identifier
	ViewType        ViewType                 `json:"view_type"`         // Type of view
	EnhancedFields  []string                 `json:"enhanced_fields"`   // Fields enhanced for role
	HiddenFields    []string                 `json:"hidden_fields"`     // Fields hidden from role
	AddedInsights   []string                 `json:"added_insights"`    // Role-specific insights added
	GeneratedAt     time.Time                `json:"generated_at"`      // When view was generated
}

// ViewType represents types of role-specific views
type ViewType string

const (
	ViewTypeDeveloper    ViewType = "developer"     // Developer-focused view
	ViewTypeArchitect    ViewType = "architect"     // Architect-focused view
	ViewTypeManager      ViewType = "manager"       // Manager-focused view
	ViewTypeSecurity     ViewType = "security"      // Security-focused view
	ViewTypeAuditor      ViewType = "auditor"       // Auditor-focused view
	ViewTypeOperations   ViewType = "operations"    // Operations-focused view
)

// FilteringPolicy represents context filtering policy configuration
type FilteringPolicy struct {
	ID              string                 `json:"id"`               // Policy ID
	Name            string                 `json:"name"`             // Policy name
	Rules           []*FilteringRule       `json:"rules"`            // Filtering rules
	DefaultAction   FilterAction           `json:"default_action"`   // Default action
	Priority        int                    `json:"priority"`         // Policy priority
	ApplicableRoles []string               `json:"applicable_roles"` // Roles this applies to
	CreatedAt       time.Time              `json:"created_at"`       // When created
	UpdatedAt       time.Time              `json:"updated_at"`       // When updated
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// FilteringRule represents a single filtering rule
type FilteringRule struct {
	ID              string                 `json:"id"`               // Rule ID
	Name            string                 `json:"name"`             // Rule name
	Condition       string                 `json:"condition"`        // Rule condition expression
	Action          FilterAction           `json:"action"`           // Action to take
	TargetFields    []string               `json:"target_fields"`    // Fields affected by rule
	Priority        int                    `json:"priority"`         // Rule priority
	Enabled         bool                   `json:"enabled"`          // Whether rule is enabled
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// FilterAction represents actions that can be taken during filtering
type FilterAction string

const (
	FilterActionAllow     FilterAction = "allow"      // Allow field/content
	FilterActionDeny      FilterAction = "deny"       // Deny field/content
	FilterActionRedact    FilterAction = "redact"     // Redact field/content
	FilterActionTransform FilterAction = "transform"  // Transform field/content
	FilterActionAudit     FilterAction = "audit"      // Allow but audit access
)

// ConditionalPermission represents a permission with conditions
type ConditionalPermission struct {
	Permission      Permission             `json:"permission"`       // Base permission
	Conditions      []*PermissionCondition `json:"conditions"`       // Required conditions
	ExpiresAt       *time.Time             `json:"expires_at,omitempty"` // When permission expires
	GrantedAt       time.Time              `json:"granted_at"`       // When permission was granted
	GrantedBy       string                 `json:"granted_by"`       // Who granted permission
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// EvaluationContext represents context for permission evaluation
type EvaluationContext struct {
	UserID          string                 `json:"user_id"`          // User identifier
	Resource        string                 `json:"resource"`         // Resource being accessed
	Action          string                 `json:"action"`           // Action being attempted
	Environment     map[string]interface{} `json:"environment"`      // Environmental context
	RequestTime     time.Time              `json:"request_time"`     // When request was made
	ClientInfo      *ClientInfo            `json:"client_info"`      // Client information
	PreviousDecisions []*AccessDecision    `json:"previous_decisions"` // Previous related decisions
}

// ClientInfo represents information about the client making the request
type ClientInfo struct {
	IPAddress       string                 `json:"ip_address"`       // Client IP address
	UserAgent       string                 `json:"user_agent"`       // Client user agent
	Location        *LocationInfo          `json:"location,omitempty"` // Client location
	DeviceInfo      map[string]interface{} `json:"device_info"`      // Device information
	SessionInfo     *SessionInfo           `json:"session_info"`     // Session information
}

// LocationInfo represents location information
type LocationInfo struct {
	Country         string  `json:"country"`          // Country code
	Region          string  `json:"region"`           // Region/state
	City            string  `json:"city"`             // City name
	Latitude        float64 `json:"latitude"`         // Latitude
	Longitude       float64 `json:"longitude"`        // Longitude
	Accuracy        float64 `json:"accuracy"`         // Location accuracy
}

// SessionInfo represents session information
type SessionInfo struct {
	SessionID       string    `json:"session_id"`       // Session identifier
	CreatedAt       time.Time `json:"created_at"`       // When session was created
	LastActivity    time.Time `json:"last_activity"`    // Last activity time
	ActivityCount   int       `json:"activity_count"`   // Number of activities
	RiskScore       float64   `json:"risk_score"`       // Session risk score
}

// PermissionEvaluation represents result of permission evaluation
type PermissionEvaluation struct {
	Permission      Permission             `json:"permission"`       // Evaluated permission
	Granted         bool                   `json:"granted"`          // Whether permission was granted
	Reason          string                 `json:"reason"`           // Evaluation reason
	ConditionResults []*ConditionResult    `json:"condition_results"` // Individual condition results
	EvaluationTime  time.Duration          `json:"evaluation_time"`  // Time taken to evaluate
	EvaluatedAt     time.Time              `json:"evaluated_at"`     // When evaluation occurred
	CacheHit        bool                   `json:"cache_hit"`        // Whether result was cached
}

// ConditionResult represents result of condition evaluation
type ConditionResult struct {
	Condition       *PermissionCondition   `json:"condition"`        // Evaluated condition
	Satisfied       bool                   `json:"satisfied"`        // Whether condition was satisfied
	Value           interface{}            `json:"value"`            // Condition value
	EvaluationTime  time.Duration          `json:"evaluation_time"`  // Time taken to evaluate
	ErrorMessage    string                 `json:"error_message,omitempty"` // Error if evaluation failed
}

// PermissionRule represents a custom permission evaluation rule
type PermissionRule struct {
	ID              string                 `json:"id"`               // Rule ID
	Name            string                 `json:"name"`             // Rule name
	Description     string                 `json:"description"`      // Rule description
	RuleType        RuleType               `json:"rule_type"`        // Type of rule
	Expression      string                 `json:"expression"`       // Rule expression
	ApplicablePermissions []Permission     `json:"applicable_permissions"` // Permissions this applies to
	Priority        int                    `json:"priority"`         // Rule priority
	Enabled         bool                   `json:"enabled"`          // Whether rule is enabled
	CreatedAt       time.Time              `json:"created_at"`       // When created
	UpdatedAt       time.Time              `json:"updated_at"`       // When updated
	CreatedBy       string                 `json:"created_by"`       // Who created rule
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// RuleType represents types of permission rules
type RuleType string

const (
	RuleTypeAllow       RuleType = "allow"        // Allow rule
	RuleTypeDeny        RuleType = "deny"         // Deny rule
	RuleTypeConditional RuleType = "conditional"  // Conditional rule
	RuleTypeTransform   RuleType = "transform"    // Transform rule
	RuleTypeAudit       RuleType = "audit"        // Audit rule
)

// EncryptedData represents encrypted data with role-based access
type EncryptedData struct {
	Data            []byte                 `json:"data"`             // Encrypted data
	EncryptionMethod string                `json:"encryption_method"` // Encryption method used
	RoleKeys        map[string]string      `json:"role_keys"`        // Encrypted keys by role
	AccessLevels    map[string]security.AccessLevel `json:"access_levels"` // Access levels by role
	CreatedAt       time.Time              `json:"created_at"`       // When encrypted
	ExpiresAt       *time.Time             `json:"expires_at,omitempty"` // When encryption expires
	Metadata        map[string]interface{} `json:"metadata"`         // Additional metadata
}

// RoleKey represents an encryption key for a role
type RoleKey struct {
	RoleID          string                 `json:"role_id"`          // Role identifier
	KeyData         []byte                 `json:"key_data"`         // Key data (encrypted)
	KeyType         string                 `json:"key_type"`         // Key type
	CreatedAt       time.Time              `json:"created_at"`       // When key was created
	ExpiresAt       *time.Time             `json:"expires_at,omitempty"` // When key expires
	Version         int                    `json:"version"`          // Key version
	Status          KeyStatus              `json:"status"`           // Key status
}

// KeyStatus represents status of encryption keys
type KeyStatus string

const (
	KeyStatusActive    KeyStatus = "active"     // Key is active
	KeyStatusExpired   KeyStatus = "expired"    // Key has expired
	KeyStatusRevoked   KeyStatus = "revoked"    // Key has been revoked
	KeyStatusRotated   KeyStatus = "rotated"    // Key has been rotated
)

// KeyRotationResult represents result of key rotation
type KeyRotationResult struct {
	RotatedRoles    []string               `json:"rotated_roles"`    // Roles for which keys were rotated
	NewKeys         map[string]*RoleKey    `json:"new_keys"`         // New keys by role
	RevokedKeys     map[string]*RoleKey    `json:"revoked_keys"`     // Revoked keys by role
	RotationTime    time.Duration          `json:"rotation_time"`    // Time taken for rotation
	RotatedAt       time.Time              `json:"rotated_at"`       // When rotation occurred
	Errors          []string               `json:"errors,omitempty"` // Any errors during rotation
}