package model

import (
	"time"

	"gorm.io/gorm"
)

// User 平台用户模型（管理员、代理商）
type User struct {
	ID                  uint       `gorm:"primaryKey" json:"id"`
	Username            string     `gorm:"uniqueIndex;size:50" json:"username"`
	Email               *string    `gorm:"uniqueIndex;size:100" json:"email"`
	Password            string     `gorm:"size:255" json:"-"`
	Avatar              string     `gorm:"size:255" json:"avatar"`
	Signature           string     `gorm:"size:255" json:"signature"`
	Role                string     `gorm:"size:20;default:admin" json:"role"`
	Status              string     `gorm:"size:20;default:active" json:"status"`
	DeviceID            string     `gorm:"size:100" json:"device_id"`
	LastLoginAt         *time.Time `json:"last_login_at"`
	ResetToken          string     `gorm:"size:255" json:"-"`
	ResetTokenExpiresAt *time.Time `json:"reset_token_expires_at"`

	CurrentPackageID *uint      `json:"current_package_id"`
	ApiCallsUsed     int        `gorm:"default:0" json:"api_calls_used"`
	StorageUsed      int64      `gorm:"default:0" json:"storage_used"`
	ApiCallsResetAt  *time.Time `json:"api_calls_reset_at"`
	ApiToken         string     `gorm:"size:64" json:"api_token"`

	ParentAgentID    *uint   `gorm:"index" json:"parent_agent_id"`
	CanCreateAgent   bool    `gorm:"default:false" json:"can_create_agent"`
	Balance          float64 `gorm:"default:0" json:"balance"`

	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`

	Applications      []Application      `gorm:"foreignKey:UserID" json:"-"`
	AgentApplications []AgentApplication `gorm:"foreignKey:AgentID" json:"-"`
	CurrentPackage    *Package           `gorm:"foreignKey:CurrentPackageID" json:"current_package,omitempty"`
	ParentAgent       *User              `gorm:"foreignKey:ParentAgentID" json:"parent_agent,omitempty"`
	ChildAgents       []User             `gorm:"foreignKey:ParentAgentID" json:"child_agents,omitempty"`
}

// AppUser 应用用户模型（应用对接的用户）
type AppUser struct {
	ID              uint           `gorm:"primaryKey" json:"id"`
	Username        string         `gorm:"uniqueIndex:idx_app_user;size:50" json:"username"`
	Email           string         `gorm:"size:100" json:"email"`
	Password        string         `gorm:"size:255" json:"-"`
	DeviceID        string         `gorm:"size:100" json:"device_id"`
	Avatar          string         `gorm:"size:255" json:"avatar"`
	Status          string         `gorm:"size:20;default:active" json:"status"`
	ApplicationID   uint           `gorm:"index:idx_app_user;not null" json:"application_id"`
	Balance         float64        `gorm:"default:0" json:"balance"`
	ExpiryAt        *time.Time     `json:"expiry_at"`
	LastLoginAt     *time.Time     `json:"last_login_at"`
	LastHeartbeatAt *time.Time     `json:"last_heartbeat_at"`
	IsTrialUser     bool           `gorm:"default:false" json:"is_trial_user"`
	TrialStartAt    *time.Time     `json:"trial_start_at"`
	TrialEndAt      *time.Time     `json:"trial_end_at"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	DeletedAt       gorm.DeletedAt `gorm:"index" json:"-"`

	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

type PaymentChannel struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	Name      string         `gorm:"size:100;not null" json:"name"`
	Type      string         `gorm:"size:50;not null" json:"type"`
	Icon      string         `gorm:"size:100" json:"icon"`
	Config    string         `gorm:"type:text" json:"config"`
	Sort      int            `gorm:"default:0" json:"sort"`
	Status    string         `gorm:"size:20;default:active" json:"status"`
	Remark    string         `gorm:"size:500" json:"remark"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

type EmailConfig struct {
	ID           uint           `gorm:"primaryKey" json:"id"`
	Name         string         `gorm:"size:100;not null" json:"name"`
	SMTPHost     string         `gorm:"size:100;not null" json:"smtp_host"`
	SMTPPort     int            `gorm:"not null" json:"smtp_port"`
	SMTPUser     string         `gorm:"size:100;not null" json:"smtp_user"`
	SMTPPassword string         `gorm:"size:255" json:"smtp_password"`
	SMTPFrom     string         `gorm:"size:100;not null" json:"smtp_from"`
	SMTPFromName string         `gorm:"size:100" json:"smtp_from_name"`
	Encryption   string         `gorm:"size:20;default:tls" json:"encryption"`
	Status       string         `gorm:"size:20;default:active" json:"status"`
	Remark       string         `gorm:"size:500" json:"remark"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	DeletedAt    gorm.DeletedAt `gorm:"index" json:"-"`
}

type SmsConfig struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	Name      string         `gorm:"size:100;not null" json:"name"`
	Type      string         `gorm:"size:20;not null" json:"type"`
	Config    string         `gorm:"type:text" json:"config"`
	Status    string         `gorm:"size:20;default:active" json:"status"`
	Remark    string         `gorm:"size:500" json:"remark"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}

type StorageConfig struct {
	ID           uint           `gorm:"primaryKey" json:"id"`
	Name         string         `gorm:"size:100;not null" json:"name"`
	Type         string         `gorm:"size:20;not null" json:"type"`
	Endpoint     string         `gorm:"size:255" json:"endpoint"`
	Bucket       string         `gorm:"size:100" json:"bucket"`
	AccessKey    string         `gorm:"size:255" json:"access_key"`
	SecretKey    string         `gorm:"size:255" json:"secret_key"`
	Region       string         `gorm:"size:50" json:"region"`
	PathPrefix   string         `gorm:"size:255" json:"path_prefix"`
	IsDefault    bool           `gorm:"default:false" json:"is_default"`
	Status       string         `gorm:"size:20;default:active" json:"status"`
	Remark       string         `gorm:"size:500" json:"remark"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	DeletedAt    gorm.DeletedAt `gorm:"index" json:"-"`
}

// DynamicCode 动态代码模型
type DynamicCode struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	ApplicationID uint           `gorm:"index;not null" json:"application_id"`
	Name          string         `gorm:"size:100;not null" json:"name"`
	Key           string         `gorm:"size:100;uniqueIndex;not null" json:"key"`
	Code          string         `gorm:"type:longtext;not null" json:"code"`
	Description   string         `gorm:"type:text" json:"description"`
	Status        string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
	Creator     *User       `gorm:"foreignKey:UserID" json:"creator,omitempty"`
	UserID      *uint       `gorm:"index" json:"user_id"`
}

// UserLevel 用户等级模型
type UserLevel struct {
	ID             uint           `gorm:"primaryKey" json:"id"`
	Name           string         `gorm:"size:50" json:"name"`
	Description    string         `gorm:"size:255" json:"description"`
	RequiredPoints int            `gorm:"default:0" json:"required_points"`
	Discount       int            `gorm:"default:100" json:"discount"`
	IsDefault      bool           `gorm:"default:false" json:"is_default"`
	CreatedAt      time.Time      `json:"created_at"`
	UpdatedAt      time.Time      `json:"updated_at"`
	DeletedAt      gorm.DeletedAt `gorm:"index" json:"-"`
}

// Application 应用模型
type Application struct {
	ID                     uint           `gorm:"primaryKey" json:"id"`
	UserID                 uint           `json:"user_id"`
	Name                   string         `gorm:"size:100" json:"name"`
	Description            string         `gorm:"type:text" json:"description"`
	IconURL                string         `gorm:"size:255" json:"icon_url"`
	AppKey                 string         `gorm:"uniqueIndex;size:50" json:"app_key"`
	BillingType            string         `gorm:"size:20" json:"billing_type"`
	LoginPolicy            string         `gorm:"size:20;default:loose" json:"login_policy"`
	EncryptType            string         `gorm:"size:20" json:"encrypt_type"`
	EncryptKey             string         `gorm:"size:255" json:"encrypt_key"`
	BindType               string         `gorm:"size:20" json:"bind_type"`
	MaxDevices             int            `gorm:"default:1" json:"max_devices"`
	ChangeLimit            int            `gorm:"default:3" json:"change_limit"`
	ChangeInterval         int            `gorm:"default:7" json:"change_interval"`
	ChangeExceedAction     string         `gorm:"size:20;default:deny" json:"change_exceed_action"`
	ChangeDeductAmount     float64        `gorm:"default:1" json:"change_deduct_amount"`
	MultiOpenMode          string         `gorm:"size:20;default:forbidden" json:"multi_open_mode"`
	MaxInstances           int            `gorm:"default:1" json:"max_instances"`
	EnableTrial            bool           `gorm:"default:false" json:"enable_trial"`
	TrialBalance           float64        `gorm:"default:0" json:"trial_balance"`
	TrialDays              int            `gorm:"default:0" json:"trial_days"`
	EnableFreePeriod       bool           `gorm:"default:false" json:"enable_free_period"`
	FreePeriodType         string         `gorm:"size:20;default:range" json:"free_period_type"`
	FreePeriodStart        string         `gorm:"size:50" json:"free_period_start"`
	FreePeriodEnd          string         `gorm:"size:50" json:"free_period_end"`
	FreePeriodWeekdays     string         `gorm:"size:50" json:"free_period_weekdays"`
	FreePeriodStartTime    string         `gorm:"size:10" json:"free_period_start_time"`
	FreePeriodEndTime      string         `gorm:"size:10" json:"free_period_end_time"`
	HeartbeatInterval      int            `gorm:"default:60" json:"heartbeat_interval"`
	HeartbeatTimeout       int            `gorm:"default:300" json:"heartbeat_timeout"`
	MaxAttempts            int            `gorm:"default:5" json:"max_attempts"`
	LockDuration           int            `gorm:"default:30" json:"lock_duration"`
	Status                 string         `gorm:"size:20;default:active" json:"status"`
	DeductionMode          string         `gorm:"size:20;default:auto" json:"deduction_mode"`
	DeductionType          string         `gorm:"size:20;default:login" json:"deduction_type"`
	DeductionInterval      int            `gorm:"default:1" json:"deduction_interval"`
	DeductionUnit          string         `gorm:"size:20;default:minute" json:"deduction_unit"`
	DeductionAmount        float64        `gorm:"default:1" json:"deduction_amount"`
	AllowRegister          bool           `gorm:"default:true" json:"allow_register"`
	EnableLoginVerify      bool           `gorm:"default:false" json:"enable_login_verify"`
	EnableRegisterVerify   bool           `gorm:"default:false" json:"enable_register_verify"`
	VerifyMethod           string         `gorm:"size:20;default:email" json:"verify_method"`
	EmailConfigID          *uint          `json:"email_config_id"`
	SmsConfigID            *uint          `json:"sms_config_id"`
	EnablePasswordReset    bool           `gorm:"default:false" json:"enable_password_reset"`
	PasswordResetMethod    string         `gorm:"size:20;default:email" json:"password_reset_method"`
	PasswordResetEmailID   *uint          `json:"password_reset_email_id"`
	PasswordResetSmsID     *uint          `json:"password_reset_sms_id"`
	CreatedAt              time.Time      `json:"created_at"`
	UpdatedAt              time.Time      `json:"updated_at"`
	DeletedAt              gorm.DeletedAt `gorm:"index" json:"-"`

	User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// Version 版本模型
type Version struct {
	ID             uint           `gorm:"primaryKey" json:"id"`
	ApplicationID  uint           `json:"application_id"`
	Version        string         `gorm:"size:50" json:"version"`
	FilePath       string         `gorm:"size:255" json:"file_path"`
	FileSize       int64          `json:"file_size"`
	FileHash       string         `gorm:"size:64" json:"file_hash"`
	EntryFile      string         `gorm:"size:255" json:"entry_file"`
	ForceUpdate    bool           `gorm:"default:false" json:"force_update"`
	UpdateStrategy string         `gorm:"size:20;default:optional" json:"update_strategy"`
	UpdateMethod   string         `gorm:"size:20;default:manual" json:"update_method"`
	MinVersion     string         `gorm:"size:50" json:"min_version"`
	Description    string         `gorm:"type:text" json:"description"`
	Changelog      string         `gorm:"type:text" json:"changelog"`
	Status         string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt      time.Time      `json:"created_at"`
	UpdatedAt      time.Time      `json:"updated_at"`
	DeletedAt      gorm.DeletedAt `gorm:"index" json:"-"`

	Application Application    `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
	Files       []VersionFile  `gorm:"foreignKey:VersionID" json:"files,omitempty"`
}

// VersionFile 版本文件模型
type VersionFile struct {
	ID         uint           `gorm:"primaryKey" json:"id"`
	VersionID  uint           `json:"version_id"`
	FilePath   string         `gorm:"size:500" json:"file_path"`
	FileName   string         `gorm:"size:255" json:"file_name"`
	FileSize   int64          `json:"file_size"`
	FileHash   string         `gorm:"size:64" json:"file_hash"`
	FileType   string         `gorm:"size:20;default:resource" json:"file_type"`
	IsRequired bool           `gorm:"default:true" json:"is_required"`
	SortOrder  int            `gorm:"default:0" json:"sort_order"`
	CreatedAt  time.Time      `json:"created_at"`
	UpdatedAt  time.Time      `json:"updated_at"`
	DeletedAt  gorm.DeletedAt `gorm:"index" json:"-"`

	Version Version `gorm:"foreignKey:VersionID" json:"version,omitempty"`
}

// CardType 卡密类型模型
type CardType struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	UserID        uint           `json:"user_id"`
	ApplicationID uint           `json:"application_id"`
	Name          string         `gorm:"size:100" json:"name"`
	RechargeType  string         `gorm:"size:20;default:balance" json:"recharge_type"` // balance(余额充值), subscription(订阅充值)
	Value         float64        `json:"value"`                                        // 余额值或订阅时长(秒)
	ValueUnit     string         `gorm:"size:20;default:day" json:"value_unit"`        // 时长单位: day, month, year (仅订阅充值)
	Price         float64        `json:"price"`
	Description   string         `gorm:"type:text" json:"description"`
	Status        string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	User        User         `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application *Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// Card 卡密模型
type Card struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	ApplicationID uint           `json:"application_id"` // 所属应用ID
	CardTypeID    uint           `json:"card_type_id"`
	CardKey       string         `gorm:"uniqueIndex;size:100" json:"card_key"`
	CreatorID     uint           `json:"creator_id"`                           // 创建人ID
	AppUserID     *uint          `json:"app_user_id"`                          // 使用者ID
	Status        string         `gorm:"size:20;default:unused" json:"status"` // unused, used, banned
	UsedAt        *time.Time     `json:"used_at"`
	ExpireAt      *time.Time     `json:"expire_at"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	Application *Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
	CardType    CardType     `gorm:"foreignKey:CardTypeID" json:"card_type,omitempty"`
	Creator     User         `gorm:"foreignKey:CreatorID" json:"creator,omitempty"`
	AppUser     *AppUser     `gorm:"foreignKey:AppUserID" json:"app_user,omitempty"`
}

// Announcement 公告模型
type Announcement struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	ApplicationID uint           `json:"application_id"`
	Title         string         `gorm:"size:255" json:"title"`
	Content       string         `gorm:"type:text" json:"content"`
	Type          string         `gorm:"size:20;default:info" json:"type"`    // info, warning, urgent
	Status        string         `gorm:"size:20;default:draft" json:"status"` // draft, active
	IsTop         bool           `gorm:"default:false" json:"is_top"`         // 是否置顶
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// Order 订单模型
type Order struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	OrderNo       string         `gorm:"uniqueIndex;size:100" json:"order_no"`
	UserID        uint           `json:"user_id"`
	ApplicationID *uint          `json:"application_id"`
	PackageID     *uint          `json:"package_id"`
	OrderType     string         `gorm:"size:50;not null" json:"order_type"` // card_recharge, agent_auth, user_recharge, user_deduct, package
	Title         string         `gorm:"size:200" json:"title"`
	Amount        float64        `gorm:"type:decimal(10,2)" json:"amount"`
	PaymentType   string         `gorm:"size:50" json:"payment_type"` // alipay, wechat, balance, card, system
	PaymentMethod string         `gorm:"size:50" json:"payment_method"`
	Status        string         `gorm:"size:20;default:pending" json:"status"` // pending, paid, cancelled, refunded, failed
	PaymentAt     *time.Time     `json:"payment_at"`
	RefundAt      *time.Time     `json:"refund_at"`
	RefundReason  string         `gorm:"type:text" json:"refund_reason"`
	Description   string         `gorm:"type:text" json:"description"`
	ExtraData     string         `gorm:"type:text" json:"extra_data"` // JSON格式存储额外数据
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	User        User        `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
	Package     *Package    `gorm:"foreignKey:PackageID" json:"package,omitempty"`
}

// Log 日志模型
type Log struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	UserID        *uint          `json:"user_id"`
	ApplicationID *uint          `json:"application_id"`
	AppUserID     *uint          `json:"app_user_id"`
	LogType       string         `gorm:"size:20;default:operation" json:"log_type"` // operation, verification, exception
	Action        string         `gorm:"size:100" json:"action"`
	Resource      string         `gorm:"size:100" json:"resource"`
	ResourceID    *uint          `json:"resource_id"`
	Details       string         `gorm:"type:text" json:"details"`
	IPAddress     string         `gorm:"size:50" json:"ip_address"`
	UserAgent     string         `gorm:"size:500" json:"user_agent"`
	DeviceID      string         `gorm:"size:100" json:"device_id"`
	Status        string         `gorm:"size:20;default:success" json:"status"` // success, failed, pending
	Level         string         `gorm:"size:20;default:info" json:"level"`     // info, warning, error
	ErrorMessage  string         `gorm:"type:text" json:"error_message"`
	StackTrace    string         `gorm:"type:text" json:"stack_trace"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	User        *User    `gorm:"foreignKey:UserID" json:"user"`
	Application *Application `gorm:"foreignKey:ApplicationID" json:"application"`
	AppUser     *AppUser `gorm:"foreignKey:AppUserID" json:"app_user"`
}

// RechargeRecord 充值记录模型
type RechargeRecord struct {
	ID          uint           `gorm:"primaryKey" json:"id"`
	UserID      uint           `json:"user_id"`
	OrderNo     string         `gorm:"size:50;uniqueIndex" json:"order_no"`
	CardID      *uint          `json:"card_id"`
	CardCode    string         `gorm:"size:100" json:"card_code"`
	Amount      float64        `gorm:"type:decimal(10,2)" json:"amount"`
	Status      string         `gorm:"size:20;default:pending" json:"status"` // pending, success, failed
	PaymentType string         `gorm:"size:50" json:"payment_type"`           // card, alipay, wechat, balance
	Remark      string         `gorm:"type:text" json:"remark"`
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `gorm:"index" json:"-"`

	AppUser *AppUser `gorm:"foreignKey:UserID" json:"app_user,omitempty"`
	Card    *Card    `gorm:"foreignKey:CardID" json:"card,omitempty"`
}

// ConsumptionRecord 消费记录模型
type ConsumptionRecord struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	UserID        uint           `json:"user_id"`
	ApplicationID uint           `json:"application_id"`
	OrderNo       string         `gorm:"size:50;uniqueIndex" json:"order_no"`
	Type          string         `gorm:"size:50" json:"type"` // verification, card_purchase, subscription, feature, manual_deduct
	Content       string         `gorm:"type:text" json:"content"`
	Description   string         `gorm:"type:text" json:"description"`
	Amount        float64        `gorm:"type:decimal(10,2)" json:"amount"`
	BalanceAfter  float64        `gorm:"type:decimal(10,2)" json:"balance_after"`
	Status        string         `gorm:"size:20;default:success" json:"status"` // pending, success, failed
	PaymentType   string         `gorm:"size:50" json:"payment_type"`           // alipay, wechat, balance
	Remark        string         `gorm:"type:text" json:"remark"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	AppUser *AppUser `gorm:"foreignKey:UserID" json:"app_user,omitempty"`
}

// Ticket 工单模型
type Ticket struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	UserID        uint           `json:"user_id"`
	ApplicationID *uint          `json:"application_id"` // 关联的应用ID，如果为空则提交给平台
	Title         string         `gorm:"size:200" json:"title"`
	Content       string         `gorm:"type:text" json:"content"`
	Category      string         `gorm:"size:50" json:"category"`                // account, payment, technical, feature, other
	Type          string         `gorm:"size:50" json:"type"`                    // user, agent, admin
	Status        string         `gorm:"size:20;default:open" json:"status"`     // open, processing, resolved, closed
	Priority      string         `gorm:"size:20;default:normal" json:"priority"` // low, normal, high, urgent
	AssignedTo    *uint          `json:"assigned_to"`                            // 分配给的应用开发者ID或平台管理员ID
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	User         User          `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application  *Application  `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
	AssignedUser *User         `gorm:"foreignKey:AssignedTo" json:"assigned_user,omitempty"`
	Replies      []TicketReply `gorm:"foreignKey:TicketID" json:"replies,omitempty"`
}

// TicketReply 工单回复模型
type TicketReply struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	TicketID  uint           `json:"ticket_id"`
	UserID    uint           `json:"user_id"`
	Content   string         `gorm:"type:text" json:"content"`
	IsAdmin   bool           `gorm:"default:false" json:"is_admin"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`

	Ticket Ticket `gorm:"foreignKey:TicketID" json:"ticket,omitempty"`
	User   User   `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// UserVariable 用户变量模型
type UserVariable struct {
	ID           uint      `gorm:"primaryKey" json:"id"`
	UserID       uint      `json:"user_id"`
	AppID        uint      `json:"app_id"`
	VarName      string    `gorm:"size:100" json:"var_name"`
	VarValue     string    `gorm:"type:text" json:"var_value"`
	VarType      string    `gorm:"size:20;default:string" json:"var_type"`
	FilePath     string    `gorm:"size:500" json:"file_path"`
	FileSize     int64     `json:"file_size"`
	MimeType     string    `gorm:"size:100" json:"mime_type"`
	OriginalName string    `gorm:"size:255" json:"original_name"`
	FileMD5      string    `gorm:"size:32" json:"file_md5"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

// CloudConstant 云端常量模型
type CloudConstant struct {
	ID           uint           `gorm:"primaryKey" json:"id"`
	UserID       uint           `json:"user_id"`
	AppID        *uint          `json:"app_id"`
	Key          string         `gorm:"size:100;index" json:"key"`
	Value        string         `gorm:"type:text" json:"value"`
	VarType      string         `gorm:"size:20;default:string" json:"var_type"` // string, integer, decimal, binary
	FilePath     string         `gorm:"size:500" json:"file_path"`
	FileSize     int64          `json:"file_size"`
	MimeType     string         `gorm:"size:100" json:"mime_type"`
	OriginalName string         `gorm:"size:255" json:"original_name"`
	FileMD5      string         `gorm:"size:32" json:"file_md5"`
	Description  string         `gorm:"size:255" json:"description"`
	Status       string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	DeletedAt    gorm.DeletedAt `gorm:"index" json:"-"`

	User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// RiskControlRule 风控规则模型
type RiskControlRule struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	UserID        uint           `gorm:"index;not null" json:"user_id"`                              // 创建者ID
	ApplicationID *uint          `gorm:"index" json:"application_id"`                                 // 应用ID，为空表示全局规则
	Type          string         `gorm:"size:20;not null" json:"type"`                                // ip, device, user, region
	Value         string         `gorm:"size:255;not null" json:"value"`
	Reason        string         `gorm:"size:500" json:"reason"`
	Status        string         `gorm:"size:20;default:active" json:"status"` // active, inactive
	ExpiresAt     *time.Time     `json:"expires_at"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	User        User        `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}
type CloudVariable struct {
	ID              uint           `gorm:"primaryKey" json:"id"`
	UserID          uint           `json:"user_id"`
	AppID           *uint          `json:"app_id"`
	Key             string         `gorm:"size:100;index" json:"key"`
	DefaultValue    string         `gorm:"type:text" json:"default_value"`
	VarType         string         `gorm:"size:20;default:string" json:"var_type"` // string, integer, decimal, binary, stream
	MaxRecords      int            `gorm:"default:0" json:"max_records"`
	FilePath        string         `gorm:"size:500" json:"file_path"`
	FileSize        int64          `json:"file_size"`
	MimeType        string         `gorm:"size:100" json:"mime_type"`
	OriginalName    string         `gorm:"size:255" json:"original_name"`
	FileMD5         string         `gorm:"size:32" json:"file_md5"`
	Scope           string         `gorm:"size:20;default:app" json:"scope"`
	WritePermission string         `gorm:"size:20;default:admin" json:"write_permission"`
	Description     string         `gorm:"size:255" json:"description"`
	Status          string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	DeletedAt       gorm.DeletedAt `gorm:"index" json:"-"`

	User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

type CloudVariableRecord struct {
	ID              uint           `gorm:"primaryKey" json:"id"`
	CloudVariableID uint           `gorm:"index;not null" json:"cloud_variable_id"`
	AppUserID       *uint          `json:"app_user_id"`
	Data            string         `gorm:"type:text" json:"data"`
	CreatedAt       time.Time      `json:"created_at"`

	CloudVariable CloudVariable `gorm:"foreignKey:CloudVariableID" json:"cloud_variable,omitempty"`
}

// IPBlacklist IP黑名单模型
type IPBlacklist struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	UserID    uint           `json:"user_id"`
	IPAddress string         `gorm:"size:50" json:"ip_address"`
	Type      string         `gorm:"size:20;default:single" json:"type"` // single, range
	Reason    string         `gorm:"size:255" json:"reason"`
	ExpiresAt *time.Time     `json:"expires_at"`
	Status    string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`

	User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// DeviceBlacklist 机器码黑名单模型
type DeviceBlacklist struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	UserID    uint           `json:"user_id"`
	DeviceID  string         `gorm:"size:100" json:"device_id"`
	Type      string         `gorm:"size:20;default:temporary" json:"type"` // permanent, temporary
	Reason    string         `gorm:"size:255" json:"reason"`
	ExpiresAt *time.Time     `json:"expires_at"`
	Status    string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`

	User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// AbnormalBehavior 异常行为模型
type AbnormalBehavior struct {
	ID          uint           `gorm:"primaryKey" json:"id"`
	UserID      *uint          `json:"user_id"`
	DeviceID    string         `gorm:"size:100" json:"device_id"`
	IPAddress   string         `gorm:"size:50" json:"ip_address"`
	Type        string         `gorm:"size:50" json:"type"`  // frequent-login, abnormal-api, data-tampering, suspicious-activity
	Level       string         `gorm:"size:20" json:"level"` // low, medium, high, critical
	Description string         `gorm:"type:text" json:"description"`
	Details     string         `gorm:"type:text" json:"details"`              // JSON格式的详细信息
	Status      string         `gorm:"size:20;default:pending" json:"status"` // pending, handled, ignored
	CreatedAt   time.Time      `json:"created_at"`
	UpdatedAt   time.Time      `json:"updated_at"`
	DeletedAt   gorm.DeletedAt `gorm:"index" json:"-"`

	User *User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// DocCategory 文档分类模型
type DocCategory struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	Name          string         `gorm:"size:100" json:"name"`
	NameEn        string         `gorm:"size:100" json:"name_en"`
	Slug          string         `gorm:"size:100;uniqueIndex" json:"slug"`
	Description   string         `gorm:"size:255" json:"description"`
	DescriptionEn string         `gorm:"size:255" json:"description_en"`
	Icon          string         `gorm:"size:50;default:file-text" json:"icon"`
	Status        string         `gorm:"size:20;default:active" json:"status"`
	Sort          int            `gorm:"default:0" json:"sort"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`
}

// AgentApplication 代理应用授权模型
type AgentApplication struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	AgentID       uint           `json:"agent_id"`
	ApplicationID uint           `json:"application_id"`
	AdminID       uint           `json:"admin_id"`
	Discount      float64        `gorm:"default:1.0" json:"discount"`
	Status        string         `gorm:"size:20;default:active" json:"status"`
	IsReceived    bool           `gorm:"default:false" json:"is_received"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	Agent       User                       `gorm:"foreignKey:AgentID;references:ID" json:"agent,omitempty"`
	Application Application                `gorm:"foreignKey:ApplicationID;references:ID" json:"application,omitempty"`
	Admin       User                       `gorm:"foreignKey:AdminID;references:ID" json:"admin,omitempty"`
	CardTypes   []AgentApplicationCardType `gorm:"foreignKey:AgentApplicationID" json:"card_types,omitempty"`
}

// AgentApplicationCardType 代理应用卡密类型授权
type AgentApplicationCardType struct {
	ID                 uint           `gorm:"primaryKey" json:"id"`
	AgentApplicationID uint           `json:"agent_application_id"`
	CardTypeID         uint           `json:"card_type_id"`
	CanGenerate        bool           `gorm:"default:false" json:"can_generate"`
	CreatedAt          time.Time      `json:"created_at"`
	DeletedAt          gorm.DeletedAt `gorm:"index" json:"-"`

	AgentApplication AgentApplication `gorm:"foreignKey:AgentApplicationID" json:"agent_application,omitempty"`
	CardType         CardType         `gorm:"foreignKey:CardTypeID" json:"card_type,omitempty"`
}

// AgentApplicationRequest 代理应用申请/邀请模型
type AgentApplicationRequest struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	AgentID       uint           `json:"agent_id"`
	AdminID       uint           `json:"admin_id"`
	ApplicationID uint           `json:"application_id"`
	Type          string         `gorm:"size:20" json:"type"`
	Status        string         `gorm:"size:20;default:pending" json:"status"`
	Message       string         `gorm:"type:text" json:"message"`
	RejectReason  string         `gorm:"type:text" json:"reject_reason"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	Agent       User        `gorm:"foreignKey:AgentID" json:"agent,omitempty"`
	Admin       User        `gorm:"foreignKey:AdminID" json:"admin,omitempty"`
	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// Package 套餐模型
type Package struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	Name          string         `gorm:"size:100" json:"name"`
	NameEn        string         `gorm:"size:100" json:"name_en"`
	Price         float64        `gorm:"default:0" json:"price"`
	Currency      string         `gorm:"size:10;default:CNY" json:"currency"` // CNY, USD, EUR, GBP, JPY
	Period        string         `gorm:"size:20;default:permanent" json:"period"` // permanent, monthly, yearly
	Description   string         `gorm:"size:255" json:"description"`
	DescriptionEn string         `gorm:"size:255" json:"description_en"`
	Status        string         `gorm:"size:20;default:active" json:"status"` // active, inactive
	Sort          int            `gorm:"default:0" json:"sort"`
	IsRecommended bool           `gorm:"default:false" json:"is_recommended"`
	AllowUpgrade  bool           `gorm:"default:true" json:"allow_upgrade"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`
}

// PackagePermission 套餐权限模型
type PackagePermission struct {
	ID               uint      `gorm:"primaryKey" json:"id"`
	PackageID        uint      `json:"package_id"`
	MaxApplications  int       `gorm:"default:1" json:"max_applications"`
	MaxStorage       int       `gorm:"default:100" json:"max_storage"`
	MaxApiCalls      int       `gorm:"default:1000" json:"max_api_calls"`
	AllowAgent       bool      `gorm:"default:false" json:"allow_agent"`
	AllowCloudData   bool      `gorm:"default:false" json:"allow_cloud_data"`
	AllowDynamicCode bool      `gorm:"default:false" json:"allow_dynamic_code"`
	AllowEmail       bool      `gorm:"default:false" json:"allow_email"`
	AllowExtension   bool      `gorm:"default:false" json:"allow_extension"`
	PrioritySupport  bool      `gorm:"default:false" json:"priority_support"`
	CreatedAt        time.Time `json:"created_at"`
	UpdatedAt        time.Time `json:"updated_at"`
}

// Doc 文档模型
type Doc struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	CategoryID    *uint          `json:"category_id"`
	Title         string         `gorm:"size:200" json:"title"`
	TitleEn       string         `gorm:"size:200" json:"title_en"`
	Slug          string         `gorm:"size:200;uniqueIndex" json:"slug"`
	Content       string         `gorm:"type:longtext" json:"content"`
	ContentEn     string         `gorm:"type:longtext" json:"content_en"`
	Summary       string         `gorm:"size:500" json:"summary"`
	SummaryEn     string         `gorm:"size:500" json:"summary_en"`
	Icon          string         `gorm:"size:50" json:"icon"`
	Sort          int            `gorm:"default:0" json:"sort"`
	Status        string         `gorm:"size:20;default:draft" json:"status"` // draft, published
	ViewCount     int            `gorm:"default:0" json:"view_count"`
	AuthorID      *uint          `json:"author_id"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	Category *DocCategory `gorm:"foreignKey:CategoryID" json:"category,omitempty"`
	Author   *User        `gorm:"foreignKey:AuthorID" json:"author,omitempty"`
}

// Setting 系统设置模型
type Setting struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	Category  string    `gorm:"size:50;index" json:"category"` // basic, email, sms, payment
	Key       string    `gorm:"size:100;uniqueIndex" json:"key"`
	Value     string    `gorm:"type:text" json:"value"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

// Captcha 验证码模型
type Captcha struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	CaptchaID string    `gorm:"uniqueIndex;size:50" json:"captcha_id"`
	Code      string    `gorm:"size:10" json:"code"`
	ExpiresAt time.Time `json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
}

type EmailVerifyCode struct {
	ID           uint      `gorm:"primaryKey" json:"id"`
	ApplicationID uint     `gorm:"index" json:"application_id"`
	Email        string    `gorm:"size:100;index" json:"email"`
	Code         string    `gorm:"size:10" json:"code"`
	Purpose      string    `gorm:"size:20;default:register" json:"purpose"`
	ExpiresAt    time.Time `json:"expires_at"`
	Used         bool      `gorm:"default:false" json:"used"`
	CreatedAt    time.Time `json:"created_at"`
}

type SmsVerifyCode struct {
	ID            uint      `gorm:"primaryKey" json:"id"`
	ApplicationID uint      `gorm:"index" json:"application_id"`
	Phone         string    `gorm:"size:20;index" json:"phone"`
	Code          string    `gorm:"size:10" json:"code"`
	Purpose       string    `gorm:"size:20;default:register" json:"purpose"`
	ExpiresAt     time.Time `json:"expires_at"`
	Used          bool      `gorm:"default:false" json:"used"`
	CreatedAt     time.Time `json:"created_at"`
}

type AppSMTPConfig struct {
	ID           uint           `gorm:"primaryKey" json:"id"`
	ApplicationID uint          `gorm:"uniqueIndex" json:"application_id"`
	Host         string         `gorm:"size:100" json:"host"`
	Port         int            `gorm:"default:465" json:"port"`
	User         string         `gorm:"size:100" json:"user"`
	Password     string         `gorm:"size:255" json:"password"`
	FromName     string         `gorm:"size:100" json:"from_name"`
	FromEmail    string         `gorm:"size:100" json:"from_email"`
	UseSSL       bool           `gorm:"default:true" json:"use_ssl"`
	Status       string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	DeletedAt    gorm.DeletedAt `gorm:"index" json:"-"`

	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

type EmailTemplate struct {
	ID           uint           `gorm:"primaryKey" json:"id"`
	ApplicationID uint          `gorm:"index" json:"application_id"`
	Type         string         `gorm:"size:50;index" json:"type"`
	Name         string         `gorm:"size:100" json:"name"`
	Subject      string         `gorm:"size:200" json:"subject"`
	Content      string         `gorm:"type:text" json:"content"`
	IsDefault    bool           `gorm:"default:false" json:"is_default"`
	Status       string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	DeletedAt    gorm.DeletedAt `gorm:"index" json:"-"`

	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// UserPackage 用户套餐授权模型
type UserPackage struct {
	ID        uint           `gorm:"primaryKey" json:"id"`
	UserID    uint           `json:"user_id"`
	PackageID uint           `json:"package_id"`
	Status    string         `gorm:"size:20;default:active" json:"status"` // active, expired, cancelled
	StartedAt time.Time      `json:"started_at"`
	ExpiredAt *time.Time     `json:"expired_at"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`

	User    User    `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Package Package `gorm:"foreignKey:PackageID" json:"package,omitempty"`
}

// UserDevice 用户设备模型（设备绑定，持久化）
type UserDevice struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	UserID        uint           `gorm:"index" json:"user_id"`
	ApplicationID uint           `gorm:"index" json:"application_id"`
	DeviceID      string         `gorm:"size:100;index" json:"device_id"`
	DeviceName    string         `gorm:"size:100" json:"device_name"`
	DeviceType    string         `gorm:"size:50" json:"device_type"`
	Status        string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	User        AppUser     `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
	Sessions    []DeviceSession `gorm:"foreignKey:DeviceID;references:ID" json:"sessions,omitempty"`
}

// DeviceSession 设备会话模型（多开实例，运行时）
type DeviceSession struct {
	ID            uint       `gorm:"primaryKey" json:"id"`
	DeviceID      uint       `gorm:"index" json:"device_id"`
	UserID        uint       `gorm:"index" json:"user_id"`
	ApplicationID uint       `gorm:"index" json:"application_id"`
	InstanceID    string     `gorm:"size:100;uniqueIndex:idx_device_instance" json:"instance_id"`
	LastHeartbeat *time.Time `json:"last_heartbeat"`
	CreatedAt     time.Time  `json:"created_at"`
	UpdatedAt     time.Time  `json:"updated_at"`

	Device      UserDevice  `gorm:"foreignKey:DeviceID" json:"device,omitempty"`
	User        AppUser     `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// UserIP 用户IP绑定模型
type UserIP struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	UserID        uint           `gorm:"index" json:"user_id"`
	ApplicationID uint           `gorm:"index" json:"application_id"`
	IPAddress     string         `gorm:"size:50;index" json:"ip_address"`
	Status        string         `gorm:"size:20;default:active" json:"status"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	User        AppUser     `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// PackHistory 加壳历史记录模型
type PackHistory struct {
	ID            uint      `gorm:"primaryKey" json:"id"`
	ApplicationID uint      `gorm:"index" json:"application_id"`
	UserID        uint      `gorm:"index" json:"user_id"`
	Filename      string    `gorm:"size:255" json:"filename"`
	FileSize      int64     `json:"file_size"`
	MD5           string    `gorm:"size:32" json:"md5"`
	DownloadURL   string    `gorm:"size:500" json:"download_url"`
	UploadTime    time.Time `json:"upload_time"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`

	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
	User        AppUser     `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// WebhookConfig Webhook配置
type WebhookConfig struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	ApplicationID uint           `gorm:"index;not null" json:"application_id"`
	Name          string         `gorm:"size:100;not null" json:"name"`
	URL           string         `gorm:"size:500;not null" json:"url"`
	SecretKey     string         `gorm:"size:255" json:"secret_key"`
	Events        string         `gorm:"type:text" json:"events"` // JSON数组存储订阅的事件类型
	Status        string         `gorm:"size:20;default:active" json:"status"`
	RetryCount    int            `gorm:"default:3" json:"retry_count"`
	Timeout       int            `gorm:"default:10" json:"timeout"` // 超时时间（秒）
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// WebhookLog Webhook发送日志
type WebhookLog struct {
	ID           uint      `gorm:"primaryKey" json:"id"`
	WebhookID    uint      `gorm:"index;not null" json:"webhook_id"`
	Event        string    `gorm:"size:50;not null" json:"event"`
	RequestData  string    `gorm:"type:text" json:"request_data"`
	ResponseCode int       `json:"response_code"`
	ResponseData string    `gorm:"type:text" json:"response_data"`
	Status       string    `gorm:"size:20" json:"status"` // success, failed, retrying
	RetryCount   int       `json:"retry_count"`
	ErrorMessage string    `gorm:"type:text" json:"error_message"`
	Duration     int       `json:"duration"` // 请求耗时（毫秒）
	CreatedAt    time.Time `json:"created_at"`

	WebhookConfig WebhookConfig `gorm:"foreignKey:WebhookID" json:"webhook,omitempty"`
}

// ExtensionAPIKey 扩展API密钥
type ExtensionAPIKey struct {
	ID            uint           `gorm:"primaryKey" json:"id"`
	ApplicationID uint           `gorm:"index;not null" json:"application_id"`
	Name          string         `gorm:"size:100;not null" json:"name"`
	AccessKey     string         `gorm:"uniqueIndex;size:64;not null" json:"access_key"`
	SecretKey     string         `gorm:"size:64;not null" json:"secret_key"`
	Permissions   string         `gorm:"type:text" json:"permissions"` // JSON数组存储权限列表
	Status        string         `gorm:"size:20;default:active" json:"status"`
	LastUsedAt    *time.Time     `json:"last_used_at"`
	ExpiresAt     *time.Time     `json:"expires_at"`
	CreatedAt     time.Time      `json:"created_at"`
	UpdatedAt     time.Time      `json:"updated_at"`
	DeletedAt     gorm.DeletedAt `gorm:"index" json:"-"`

	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// ApiUsage API调用统计模型
type ApiUsage struct {
	ID            uint      `gorm:"primaryKey" json:"id"`
	UserID        uint      `json:"user_id"`
	ApplicationID uint      `json:"application_id"`
	Endpoint      string    `gorm:"size:255" json:"endpoint"`
	Method        string    `gorm:"size:10" json:"method"`
	IPAddress     string    `gorm:"size:50" json:"ip_address"`
	UserAgent     string    `gorm:"size:500" json:"user_agent"`
	ResponseTime  int       `json:"response_time"` // 响应时间（毫秒）
	StatusCode    int       `json:"status_code"`
	Success       bool      `json:"success"`
	ErrorMessage  string    `gorm:"type:text" json:"error_message"`
	CreatedAt     time.Time `json:"created_at"`

	User        User        `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// StorageUsage 存储使用记录模型
type StorageUsage struct {
	ID            uint      `gorm:"primaryKey" json:"id"`
	UserID        uint      `json:"user_id"`
	ApplicationID *uint     `json:"application_id"`
	ResourceType  string    `gorm:"size:20" json:"resource_type"` // version, cloud_file
	ResourceID    uint      `json:"resource_id"`
	FileName      string    `gorm:"size:255" json:"file_name"`
	FileSize      int64     `json:"file_size"`
	Action        string    `gorm:"size:20" json:"action"` // upload, delete
	CreatedAt     time.Time `json:"created_at"`

	User        User         `gorm:"foreignKey:UserID" json:"user,omitempty"`
	Application *Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}

// UsageAlertRecord 用量告警记录模型
type UsageAlertRecord struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	UserID    uint      `json:"user_id"`
	Type      string    `gorm:"size:20" json:"type"`      // api_calls, storage, package_expiry
	Level     string    `gorm:"size:20" json:"level"`     // warning, critical
	Message   string    `gorm:"size:255" json:"message"`
	Usage     float64   `json:"usage"`
	Limit     float64   `json:"limit"`
	Percent   float64   `json:"percent"`
	Status    string    `gorm:"size:20;default:sent" json:"status"` // sent, read
	CreatedAt time.Time `json:"created_at"`

	User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}

// Notification 站内通知模型
type Notification struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	UserID    uint      `json:"user_id"`
	Title     string    `gorm:"size:100" json:"title"`
	Content   string    `gorm:"type:text" json:"content"`
	Type      string    `gorm:"size:20" json:"type"` // usage_alert, system, package
	IsRead    bool      `gorm:"default:false" json:"is_read"`
	CreatedAt time.Time `json:"created_at"`

	User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}
