package alerts

import "log"

// Notifier sends Telegram/email when Calibrate toggles allow it.
type Notifier struct {
	settings func() Settings
}

func NewNotifier(settings func() Settings) *Notifier {
	return &Notifier{settings: settings}
}

func (n *Notifier) Emit(event string, title, body string) {
	if n == nil || n.settings == nil {
		return
	}
	s := n.settings()
	if !n.eventEnabled(s, event) {
		return
	}
	if s.TelegramBotToken == "" && s.TelegramChatID == "" && !s.EmailEnabled && s.WebhookURL == "" {
		return
	}
	log.Printf("[Notify] %s: %s", event, body)
	NotifyAllEvent(s.NotifyConfig, event, title, body)
}

func (n *Notifier) eventEnabled(s Settings, event string) bool {
	switch event {
	case EventAgentConnect:
		return s.Events.AgentConnect
	case EventAgentReconnect:
		return s.Events.AgentReconnect
	case EventBuildComplete:
		return s.Events.BuildComplete
	case EventKEVExposure:
		return s.Events.KEVExposure
	case "offline":
		return s.Events.AgentOffline
	case "hashrate_drop":
		return s.Events.HashrateDrop
	case "rejection_rate":
		return s.Events.RejectionRate
	default:
		return true
	}
}

// GetSettings exposes current settings (alert test handler).
func (n *Notifier) GetSettings() Settings {
	if n == nil || n.settings == nil {
		return Settings{}
	}
	return n.settings()
}
