package notify

import (
	"fmt"
	"time"

	"gitea.hostxtra.co.uk/mrhid6/vantage/server/internal/models"
)

// TypeServer marks an event whose subject is a managed server rather than a
// monitor check. MonitorName carries the hostname in that case.
const TypeServer = "server"

type Event struct {
	MonitorName string
	Type        string
	OldStatus   string
	NewStatus   string
	Message     string
	Time        time.Time
}

func (e Event) title() string {
	verb := "recovered"
	if e.NewStatus == models.StatusDown {
		verb = "is DOWN"
	}
	var s string
	if e.Type == TypeVuln {
		// A digest is not a transition. MonitorName already carries the whole
		// headline ("12 new critical across 4 servers"), so no verb applies.
		s = fmt.Sprintf("[Vantage] %s", e.MonitorName)
	} else if e.Type == TypeServer {
		if e.NewStatus == models.StatusDown {
			verb = "went offline"
		} else {
			verb = "is back online"
		}
		s = fmt.Sprintf("[Vantage] Server %s %s", e.MonitorName, verb)
	} else {
		s = fmt.Sprintf("[Vantage] %s (%s) %s", e.MonitorName, e.Type, verb)
	}
	if e.Message != "" {
		s += ": " + e.Message
	}
	return s
}

func Dispatch(ch models.NotificationChannel, ev Event) error {
	switch ch.Type {
	case models.ChannelWebhook:
		return dispatchWebhook(ch, ev)
	case models.ChannelDiscord:
		return dispatchDiscord(ch, ev)
	case models.ChannelSlack:
		return dispatchSlack(ch, ev)
	case models.ChannelTelegram:
		return dispatchTelegram(ch, ev)
	case models.ChannelSMTP:
		return dispatchSMTP(ch, ev)
	default:
		return fmt.Errorf("unknown channel type: %s", ch.Type)
	}
}

func Test(ch models.NotificationChannel) error {
	return Dispatch(ch, Event{
		MonitorName: "Test monitor",
		Type:        "http",
		OldStatus:   models.StatusUp,
		NewStatus:   models.StatusDown,
		Message:     "this is a test alert from Vantage",
		Time:        time.Now(),
	})
}
