// Filename: internal/models/events.go
package models

import (
	"gemini-balancer/internal/errors"
	"time"
)

// Topic 定义事件总线主题名称
const (
	TopicRequestFinished        = "events:request_finished"
	TopicKeyStatusChanged       = "events:key_status_changed"
	TopicUpstreamHealthChanged  = "events:upstream_health_changed"
	TopicMasterKeyStatusChanged = "master_key_status_changed"
	TopicImportGroupCompleted   = "events:import_group_completed"
)

type RequestFinishedEvent struct {
	RequestLog
	Error            *errors.APIError `json:"error,omitempty"` // Error 结构体不存入数据库，仅供事件传递
	CorrelationID    string           `json:"correlation_id,omitempty"`
	UpstreamURL      *string          `json:"upstream_url,omitempty"`
	IsPreciseRouting bool             `json:"is_precise_routing"`
}

type KeyStatusChangedEvent struct {
	KeyID        uint
	GroupID      uint
	OldStatus    APIKeyStatus
	NewStatus    APIKeyStatus
	ChangeReason string    `json:"change_reason"`
	ChangedAt    time.Time `json:"changed_at"`
}

type UpstreamHealthChangedEvent struct {
	UpstreamID  uint          `json:"upstream_id"`
	UpstreamURL string        `json:"upstream_url"`
	OldStatus   string        `json:"old_status"` // e.g., "healthy", "unhealthy"
	NewStatus   string        `json:"new_status"`
	Latency     time.Duration `json:"latency_ms"` // 延迟时间(毫秒)
	Reason      string        `json:"reason"`     // 状态变更原因，如 "timeout", "status_503"
	CheckedAt   time.Time     `json:"checked_at"`
}

const TopicProxyStatusChanged = "proxy:status_changed"

type ProxyStatusChangedEvent struct {
	ProxyID uint   `json:"proxy_id"`
	Action  string `json:"action"` // "created", "updated", "deleted"
}

type MasterKeyStatusChangedEvent struct {
	KeyID           uint               `json:"key_id"`
	OldMasterStatus MasterAPIKeyStatus `json:"old_master_status"`
	NewMasterStatus MasterAPIKeyStatus `json:"new_master_status"`
	ChangeReason    string             `json:"change_reason"`
	ChangedAt       time.Time          `json:"changed_at"`
}

type ImportGroupCompletedEvent struct {
	GroupID     uint      `json:"group_id"`
	KeyIDs      []uint    `json:"key_ids"`
	CompletedAt time.Time `json:"completed_at"`
}
