package notify

import (
	"fmt"

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

// dispatchSMTP delivers a state change over one channel's own SMTP settings.
//
// The transport, the envelope and the look of the message all live in
// shared/mail, which admin and sitesvc use too — a Vantage alert and a Vantage
// licence email should not look like they came from different products. This
// function only turns a channel document into a Sender.
func dispatchSMTP(ch models.NotificationChannel, ev Event) error {
	to := ch.Config["to"]
	sender := mail.Sender{
		Host:     ch.Config["host"],
		Port:     ch.Config["port"],
		From:     ch.Config["from"],
		Username: ch.Config["username"],
		Password: ch.Config["password"],
	}
	if !sender.Enabled() || sender.Port == "" || to == "" {
		return fmt.Errorf("smtp: missing host/port/from/to")
	}

	return sender.SendMonitorAlert(to, mail.MonitorEvent{
		MonitorName: ev.MonitorName,
		Type:        ev.Type,
		OldStatus:   ev.OldStatus,
		NewStatus:   ev.NewStatus,
		Message:     ev.Message,
		Time:        ev.Time,
		Down:        ev.NewStatus == models.StatusDown,
	})
}
