package manage

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

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

// HandleUpdateSchedule speichert den Zeitplan für ein Display.
// Body: {"schedule_enabled":true,"power_on_time":"06:00","power_off_time":"22:00"}
func HandleUpdateSchedule(screens *store.ScreenStore, schedules *store.ScreenScheduleStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		screenSlug := r.PathValue("screenSlug")
		screen, err := screens.GetBySlug(r.Context(), screenSlug)
		if err != nil {
			http.Error(w, "screen not found", http.StatusNotFound)
			return
		}
		if !requireScreenAccess(w, r, screen) {
			return
		}

		var body struct {
			ScheduleEnabled bool   `json:"schedule_enabled"`
			PowerOnTime     string `json:"power_on_time"`
			PowerOffTime    string `json:"power_off_time"`
		}
		if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
			http.Error(w, "invalid JSON", http.StatusBadRequest)
			return
		}
		if body.PowerOnTime != "" {
			if _, err := time.Parse("15:04", body.PowerOnTime); err != nil {
				http.Error(w, "invalid power_on_time format (use HH:MM)", http.StatusBadRequest)
				return
			}
		}
		if body.PowerOffTime != "" {
			if _, err := time.Parse("15:04", body.PowerOffTime); err != nil {
				http.Error(w, "invalid power_off_time format (use HH:MM)", http.StatusBadRequest)
				return
			}
		}

		if err := schedules.Upsert(r.Context(), &store.ScreenSchedule{
			ScreenID:        screen.ID,
			ScheduleEnabled: body.ScheduleEnabled,
			PowerOnTime:     body.PowerOnTime,
			PowerOffTime:    body.PowerOffTime,
		}); err != nil {
			http.Error(w, "db error", http.StatusInternalServerError)
			return
		}

		w.WriteHeader(http.StatusNoContent)
	}
}
