package httpapi

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

	"git.azzamo.net/Michilis/Spanglish/photo-api/internal/store"
)

func writeJSON(w http.ResponseWriter, status int, body any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.NewEncoder(w).Encode(body); err != nil {
		log.Printf("write response: %v", err)
	}
}

// writeError follows the backend's error shape: {"error": string}.
func writeError(w http.ResponseWriter, status int, msg string) {
	writeJSON(w, status, map[string]string{"error": msg})
}

// writeStoreError maps store errors: ErrNotFound -> 404, else 500 with the
// backend's generic message (details go to the log, not the client).
func writeStoreError(w http.ResponseWriter, err error, notFoundMsg string) {
	if err == store.ErrNotFound {
		writeError(w, http.StatusNotFound, notFoundMsg)
		return
	}
	log.Printf("Error: %v", err)
	writeError(w, http.StatusInternalServerError, "Internal Server Error")
}

func decodeJSON(r *http.Request, dst any) error {
	dec := json.NewDecoder(http.MaxBytesReader(nil, r.Body, 1<<20))
	dec.DisallowUnknownFields()
	return dec.Decode(dst)
}
