package manage

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

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

// HandleRegisterScreen is called by the player agent on startup.
// It upserts the screen in the default tenant so that all
// deployed screens appear automatically in the admin UI.
//
// POST /api/v1/screens/register
// Body: {"slug":"info10","name":"Info10 Bildschirm","orientation":"landscape"}
func HandleRegisterScreen(tenants *store.TenantStore, screens *store.ScreenStore, cfg config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var body struct {
			Slug        string `json:"slug"`
			Name        string `json:"name"`
			Orientation string `json:"orientation"`
		}
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			http.Error(w, "invalid json", http.StatusBadRequest)
			return
		}

		body.Slug = strings.TrimSpace(body.Slug)
		body.Name = strings.TrimSpace(body.Name)
		if body.Slug == "" {
			http.Error(w, "slug required", http.StatusBadRequest)
			return
		}
		if body.Name == "" {
			body.Name = body.Slug
		}
		if body.Orientation == "" {
			body.Orientation = "landscape"
		}

		// Register under the configured default tenant.
		tenant, err := tenants.Get(r.Context(), cfg.DefaultTenantSlug)
		if err != nil {
			http.Error(w, "default tenant not found", http.StatusInternalServerError)
			return
		}

		screen, err := screens.Upsert(r.Context(), tenant.ID, body.Slug, body.Name, body.Orientation)
		if err != nil {
			http.Error(w, "db error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK) // 200 whether created or updated
		json.NewEncoder(w).Encode(screen) //nolint:errcheck
	}
}
