package monitor

import (
	"bytes"
	"encoding/json"
	"net/http"

	log "github.com/sirupsen/logrus"
)

// Alerter 告警系统
type Alerter struct {
	webhookURL string
}

func NewAlerter(webhookURL string) *Alerter {
	return &Alerter{webhookURL: webhookURL}
}

// Critical 发送严重告警
func (a *Alerter) Critical(message string, details map[string]interface{}) {
	log.WithFields(log.Fields(details)).Error("[CRITICAL] " + message)
	a.sendWebhook("critical", message, details)
}

// Warning 发送警告
func (a *Alerter) Warning(message string, details map[string]interface{}) {
	log.WithFields(log.Fields(details)).Warn("[WARNING] " + message)
	a.sendWebhook("warning", message, details)
}

// EmergencyPause 触发桥紧急暂停
func (a *Alerter) EmergencyPause() {
	log.Error("[EMERGENCY] Triggering bridge pause via governance multisig")
	// 实际实现：调用 Governance 合约的紧急暂停提案
	a.sendWebhook("emergency", "Bridge emergency pause triggered", nil)
}

func (a *Alerter) sendWebhook(severity, message string, details map[string]interface{}) {
	if a.webhookURL == "" {
		return
	}

	payload := map[string]interface{}{
		"severity": severity,
		"message":  message,
		"details":  details,
		"source":   "genex-bridge-monitor",
	}

	body, _ := json.Marshal(payload)
	resp, err := http.Post(a.webhookURL, "application/json", bytes.NewBuffer(body))
	if err != nil {
		log.WithError(err).Error("Failed to send webhook alert")
		return
	}
	defer resp.Body.Close()
}
