package webhook

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

	"maunium.net/go/mautrix/format"
)

const (
	messageTemplate = "\U0001f6a8" +
		` **Alerts for group "_{{ .GroupKey }}_":**{{ range .Alerts }}
` + "\u2022" + ` {{ with .Labels.severity }}{{ if eq . "critical" }}` + "\U0001f525" +
		`{{ else if eq . "warning" }}` + "\U0001f4e2" +
		`{{ else }}` + "\U0001f514" +
		`{{ end }}{{ else }}` + "\U0001f514" +
		`{{ end }} {{ .Annotations.description }}{{ end }}
@room`
)

func (s Server) handleWebhook(w http.ResponseWriter, r *http.Request) {
	if r.Header.Get("Content-Type") != "application/json" {
		writeStatus(w, http.StatusBadRequest)
		return
	}

	decoder := json.NewDecoder(r.Body)

	var payload Payload
	err := decoder.Decode(&payload)
	if err != nil {
		writeStatus(w, http.StatusBadRequest)
		return
	}

	if payload.Version != "4" {
		writeStatus(w, http.StatusBadRequest)
		return
	}

	if payload.Status != StatusFiring {
		writeStatus(w, http.StatusOK)
		return
	}

	var message bytes.Buffer
	err = s.tmpl.Execute(&message, payload)
	if err != nil {
		log.Print(err)
		writeStatus(w, http.StatusInternalServerError)
		return
	}

	evt := format.RenderMarkdown(message.String(), true, false)

	success := s.matrix.Broadcast(&evt)
	if !success {
		writeStatus(w, http.StatusInternalServerError)
	}
}
