package domain

import "time"

// WebhookEventType Webhook 事件类型
type WebhookEventType string

const (
	EventUserRegistered  WebhookEventType = "user.registered"
	EventUserLogin       WebhookEventType = "user.login"
	EventUserLogout      WebhookEventType = "user.logout"
	EventUserUpdated     WebhookEventType = "user.updated"
	EventUserDeleted     WebhookEventType = "user.deleted"
	EventUserLocked      WebhookEventType = "user.locked"
	EventPasswordChanged WebhookEventType = "user.password_changed"
	EventPasswordReset   WebhookEventType = "user.password_reset"
	EventTOTPEnabled     WebhookEventType = "user.totp_enabled"
	EventTOTPDisabled    WebhookEventType = "user.totp_disabled"
	EventLoginFailed     WebhookEventType = "user.login_failed"
	EventAnomalyDetected WebhookEventType = "security.anomaly_detected"
)

// WebhookStatus Webhook 状态
type WebhookStatus int

const (
	WebhookStatusActive   WebhookStatus = 1
	WebhookStatusInactive WebhookStatus = 0
)

// Webhook Webhook 配置
type Webhook struct {
	ID          int64         `gorm:"primaryKey;autoIncrement" json:"id"`
	Name        string        `gorm:"type:varchar(100);not null" json:"name"`
	URL         string        `gorm:"type:varchar(500);not null" json:"url"`
	Secret      string        `gorm:"type:varchar(255)" json:"-"` // HMAC 签名密钥，不返回给前端
	Events      string        `gorm:"type:text" json:"events"`    // JSON 数组，订阅的事件类型
	Status      WebhookStatus `gorm:"default:1" json:"status"`
	MaxRetries  int           `gorm:"default:3" json:"max_retries"`
	TimeoutSec  int           `gorm:"default:10" json:"timeout_sec"`
	CreatedBy   int64         `gorm:"index" json:"created_by"`
	CreatedAt   time.Time     `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt   time.Time     `gorm:"autoUpdateTime" json:"updated_at"`
}

// TableName 指定表名
func (Webhook) TableName() string {
	return "webhooks"
}

// WebhookDelivery Webhook 投递记录
type WebhookDelivery struct {
	ID           int64            `gorm:"primaryKey;autoIncrement" json:"id"`
	WebhookID    int64            `gorm:"index" json:"webhook_id"`
	EventType    WebhookEventType `gorm:"type:varchar(100)" json:"event_type"`
	Payload      string           `gorm:"type:text" json:"payload"`
	StatusCode   int              `json:"status_code"`
	ResponseBody string           `gorm:"type:text" json:"response_body"`
	Attempt      int              `gorm:"default:1" json:"attempt"`
	Success      bool             `gorm:"default:false" json:"success"`
	Error        string           `gorm:"type:text" json:"error"`
	DeliveredAt  *time.Time       `json:"delivered_at,omitempty"`
	CreatedAt    time.Time        `gorm:"autoCreateTime" json:"created_at"`
}

// TableName 指定表名
func (WebhookDelivery) TableName() string {
	return "webhook_deliveries"
}
