package handler

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
)

func (h *Handler) Fallback(w http.ResponseWriter, r *http.Request) {
	h.Logger.Debug("Fallback Request received", "method", r.Method, "path", r.URL.Path)

	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Unable to read body", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()

	// Pretty-print JSON to console
	var prettyJSON bytes.Buffer
	if err := json.Indent(&prettyJSON, body, "", "  "); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	h.Logger.Debug("Received JSON payload", "payload", prettyJSON.String())
	//fmt.Println("Received JSON payload:")
	//fmt.Println(prettyJSON.String())

	// Set content type and write back the same JSON
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(prettyJSON.Bytes())
}
