package api

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

// GET /api/v1/settings
func (h *Handler) getSettings(w http.ResponseWriter, r *http.Request) {
	settings, err := h.db.GetSettings()
	if err != nil {
		writeError(w, http.StatusInternalServerError, "Settings laden fehlgeschlagen")
		return
	}
	writeJSON(w, http.StatusOK, map[string]interface{}{"data": settings})
}

// PUT /api/v1/settings (JWT only - checked via context)
func (h *Handler) updateSettings(w http.ResponseWriter, r *http.Request) {
	// JWT-only: check that user context exists
	claims := r.Context().Value(UserContextKey)
	if claims == nil {
		writeError(w, http.StatusForbidden, "Nur mit JWT-Authentifizierung erlaubt")
		return
	}

	var body map[string]string
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		writeError(w, http.StatusBadRequest, "Ungueltige Anfrage")
		return
	}

	allowedKeys := map[string]bool{
		"backend_url_internal": true,
		"backend_url_external": true,
		"api_key":              true,
	}

	var changed []string
	for k, v := range body {
		if !allowedKeys[k] {
			continue
		}
		if err := h.db.SetSetting(k, v); err != nil {
			writeError(w, http.StatusInternalServerError, fmt.Sprintf("Setting '%s' speichern fehlgeschlagen", k))
			return
		}
		changed = append(changed, k)
	}

	if len(changed) > 0 {
		h.auditLog(r, "settings.update", "settings", "", "", "Geaendert: "+strings.Join(changed, ", "))
	}

	writeJSON(w, http.StatusOK, map[string]string{"message": "Settings aktualisiert"})
}
