package main

import (
	"database/sql"
	"time"
)

// ============================================================================
// USER & AUTHENTICATION TYPES
// ============================================================================

type Role struct {
	RoleID      string    `json:"role_id"`
	RoleName    string    `json:"role_name"`
	Description string    `json:"description"`
	RoleLevel   int       `json:"role_level"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   *time.Time `json:"updated_at"`
}

type IC3User struct {
	UserID       string    `json:"user_id"`
	Username     string    `json:"username"`
	Email        string    `json:"email"`
	FullName     string    `json:"full_name"`
	Phone        string    `json:"phone"`
	IsActive     bool      `json:"is_active"`
	IsVerified   bool      `json:"is_verified"`
	MFAEnabled   bool      `json:"mfa_enabled"`
	RoleID       string    `json:"role_id"`
	Department   string    `json:"department"`
	LocationZone string    `json:"location_zone"`
	AvatarURL    string    `json:"avatar_url"`
	LastLogin    *time.Time `json:"last_login"`
	LoginAttempts int      `json:"login_attempts"`
	LockedUntil  *time.Time `json:"locked_until"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    *time.Time `json:"updated_at"`
}

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type LoginResponse struct {
	Token    string `json:"token"`
	Username string `json:"username"`
	Role     string `json:"role"`
}

type Permission struct {
	PermissionID   string    `json:"permission_id"`
	PermissionCode string    `json:"permission_code"`
	PermissionName string    `json:"permission_name"`
	ResourceType   string    `json:"resource_type"`
	Action         string    `json:"action"`
	CreatedAt      time.Time `json:"created_at"`
}

type AuthToken struct {
	TokenID    string    `json:"token_id"`
	UserID     string    `json:"user_id"`
	TokenType  string    `json:"token_type"`
	ExpiresAt  time.Time `json:"expires_at"`
	RevokedAt  *time.Time `json:"revoked_at"`
	IPAddress  string    `json:"ip_address"`
	UserAgent  string    `json:"user_agent"`
	CreatedAt  time.Time `json:"created_at"`
}

// ============================================================================
// AI MODEL TYPES
// ============================================================================

type AIModel struct {
	ModelID        string    `json:"model_id"`
	ModelCode      string    `json:"model_code"`
	ModelName      string    `json:"model_name"`
	ModelCategory  string    `json:"model_category"`
	ModelIcon      string    `json:"model_icon"`
	ModelColor     string    `json:"model_color"`
	Description    string    `json:"description"`
	Purpose        string    `json:"purpose"`
	Version        string    `json:"version"`
	IsActive       bool      `json:"is_active"`
	IsPublic       bool      `json:"is_public"`
	ParameterCount int       `json:"parameter_count"`
	HealthScore    float64   `json:"health_score"`
	Status         string    `json:"status"`
	LastHealthCheck *time.Time `json:"last_health_check"`
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      *time.Time `json:"updated_at"`
	UpdatedBy      *string   `json:"updated_by"`
}

type AIModelParameter struct {
	ParamID            string    `json:"param_id"`
	ModelID            string    `json:"model_id"`
	ParamCode          string    `json:"param_code"`
	ParamName          string    `json:"param_name"`
	ParamDescription   string    `json:"param_description"`
	DataType           string    `json:"data_type"`
	Unit               string    `json:"unit"`
	SourceSensorType   string    `json:"source_sensor_type"`
	SamplingRateSeconds *int    `json:"sampling_rate_seconds"`
	IsRequired         bool      `json:"is_required"`
	IsActive           bool      `json:"is_active"`
	CreatedAt          time.Time `json:"created_at"`
}

type AIModelMetric struct {
	MetricID           string    `json:"metric_id"`
	ModelID            string    `json:"model_id"`
	MetricDate         string    `json:"metric_date"`
	AccuracyScore      *float64  `json:"accuracy_score"`
	PrecisionScore     *float64  `json:"precision_score"`
	F1Score            *float64  `json:"f1_score"`
	PredictionsMade    int       `json:"predictions_made"`
	FalsePositives     int       `json:"false_positives"`
	AvgConfidence      *float64  `json:"avg_confidence"`
	AvgInferenceTimeMS *float64  `json:"avg_inference_time_ms"`
	DataQualityScore   *float64  `json:"data_quality_score"`
	CreatedAt          time.Time `json:"created_at"`
}

type AIPrediction struct {
	PredictionID      string              `json:"prediction_id"`
	ModelID           string              `json:"model_id"`
	AssetID           string              `json:"asset_id"`
	AssetName         string              `json:"asset_name"`
	PredictionType    string              `json:"prediction_type"`
	PredictionValue   float64             `json:"prediction_value"`
	PredictionConfidence float64          `json:"prediction_confidence"`
	PredictionSeverity string             `json:"prediction_severity"`
	KeyFeatures       map[string]interface{} `json:"key_features"`
	Recommendation    string              `json:"recommendation"`
	IsCorrect         *bool               `json:"is_correct"`
	FeedbackGivenBy   *string             `json:"feedback_given_by"`
	FeedbackGivenAt   *time.Time          `json:"feedback_given_at"`
	CreatedAt         time.Time           `json:"created_at"`
}

type AIModelConfig struct {
	ConfigID            string                 `json:"config_id"`
	ModelID             string                 `json:"model_id"`
	ConfigName          string                 `json:"config_name"`
	ConfigDescription   string                 `json:"config_description"`
	IsActive            bool                   `json:"is_active"`
	ThresholdValues     map[string]interface{} `json:"threshold_values"`
	FeatureWeights      map[string]interface{} `json:"feature_weights"`
	Hyperparameters     map[string]interface{} `json:"hyperparameters"`
	ApprovedBy          *string                `json:"approved_by"`
	ApprovedAt          *time.Time             `json:"approved_at"`
	CreatedAt           time.Time              `json:"created_at"`
}

type AIAlertRule struct {
	RuleID         string                 `json:"rule_id"`
	ModelID        string                 `json:"model_id"`
	RuleName       string                 `json:"rule_name"`
	RuleDescription string                `json:"rule_description"`
	RuleCondition   map[string]interface{} `json:"rule_condition"`
	AlertSeverity  string                 `json:"alert_severity"`
	IsEnabled      bool                   `json:"is_enabled"`
	CreatedAt      time.Time              `json:"created_at"`
}

type AITrainingJob struct {
	JobID                 string    `json:"job_id"`
	ModelID               string    `json:"model_id"`
	JobName               string    `json:"job_name"`
	JobStatus             string    `json:"job_status"`
	TrainingSampleCount   *int      `json:"training_sample_count"`
	FinalAccuracy         *float64  `json:"final_accuracy"`
	TrainingDurationMins  *int      `json:"training_duration_minutes"`
	StartedAt             *time.Time `json:"started_at"`
	CompletedAt           *time.Time `json:"completed_at"`
	ErrorMessage          *string   `json:"error_message"`
	CreatedAt             time.Time `json:"created_at"`
	CreatedBy             *string   `json:"created_by"`
}

// ============================================================================
// API RESPONSE TYPES
// ============================================================================

type APIResponse struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data"`
	Error   *string     `json:"error,omitempty"`
	Message string      `json:"message,omitempty"`
}

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message"`
	Code    int    `json:"code"`
}

// ============================================================================
// DATABASE HELPER FUNCTIONS
// ============================================================================

func (u *IC3User) Scan(rows *sql.Rows) error {
	return rows.Scan(
		&u.UserID, &u.Username, &u.Email, &u.FullName, &u.Phone,
		&u.IsActive, &u.IsVerified, &u.MFAEnabled, &u.RoleID,
		&u.Department, &u.LocationZone, &u.AvatarURL,
		&u.LastLogin, &u.LoginAttempts, &u.LockedUntil,
		&u.CreatedAt, &u.UpdatedAt,
	)
}

func (m *AIModel) Scan(rows *sql.Rows) error {
	return rows.Scan(
		&m.ModelID, &m.ModelCode, &m.ModelName, &m.ModelCategory,
		&m.ModelIcon, &m.ModelColor, &m.Description, &m.Purpose,
		&m.Version, &m.IsActive, &m.IsPublic, &m.ParameterCount,
		&m.HealthScore, &m.Status, &m.LastHealthCheck,
		&m.CreatedAt, &m.UpdatedAt, &m.UpdatedBy,
	)
}

// ============================================================================
// NAVIGATION MENU TYPES
// ============================================================================

type NavLayer struct {
	ID          int    `json:"id" db:"id"`
	LayerNo     int    `json:"layer_no" db:"layer_no"`
	Code        string `json:"code" db:"code"`
	Label       string `json:"label" db:"label"`
	Description string `json:"description" db:"description"`
}

type NavGroup struct {
	ID        int    `json:"id" db:"id"`
	SystemID  string `json:"system_id" db:"system_id"`
	LayerID   int    `json:"layer_id" db:"layer_id"`
	Code      string `json:"code" db:"code"`
	Label     string `json:"label" db:"label"`
	Icon      string `json:"icon" db:"icon"`
	SortOrder int    `json:"sort_order" db:"sort_order"`
}

type NavItem struct {
	ID        int    `json:"id" db:"id"`
	GroupID   int    `json:"group_id" db:"group_id"`
	Code      string `json:"code" db:"code"`
	Label     string `json:"label" db:"label"`
	Route     string `json:"route" db:"route"`
	Icon      string `json:"icon" db:"icon"`
	SortOrder int    `json:"sort_order" db:"sort_order"`
	Status    string `json:"status" db:"status"`
}

type NavMenuResponse struct {
	SystemID   string         `json:"system_id"`
	SystemName string         `json:"system_name"`
	Layers     []NavLayerTree `json:"layers"`
}

type NavLayerTree struct {
	LayerNo int            `json:"layer_no"`
	Code    string         `json:"code"`
	Label   string         `json:"label"`
	Groups  []NavGroupTree `json:"groups"`
}

type NavGroupTree struct {
	ID    int       `json:"id"`
	Code  string    `json:"code"`
	Label string    `json:"label"`
	Icon  string    `json:"icon"`
	Items []NavItem `json:"items"`
}
