package manage

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

	"git.az-it.net/az/morz-infoboard/server/backend/internal/mqttnotifier"
)

// HandleDisplayCommand nimmt {"state":"on"} oder {"state":"off"} entgegen und
// schickt den entsprechenden MQTT-Befehl an den Agent.
func HandleDisplayCommand(notifier *mqttnotifier.Notifier) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		screenSlug := r.PathValue("screenSlug")

		var body struct {
			State string `json:"state"`
		}
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			http.Error(w, "invalid JSON", http.StatusBadRequest)
			return
		}

		var action string
		switch body.State {
		case "on":
			action = "display_on"
		case "off":
			action = "display_off"
		default:
			http.Error(w, `state must be "on" or "off"`, http.StatusBadRequest)
			return
		}

		if err := notifier.SendDisplayCommand(screenSlug, action); err != nil {
			slog.Error("send display command", "err", err)
			http.Error(w, "failed to send command", http.StatusBadGateway)
			return
		}

		w.WriteHeader(http.StatusNoContent)
	}
}
