package api

import (
	"encoding/json"
	"io"
	"log/slog"
	"net/http"
)

type ErrorResponse struct {
	// Statustext of Errorcode
	Status string `json:"status"`
	Error  string `json:"error"` // Error Message
}

func MountApiEndpoints(r *http.ServeMux) {
	r.HandleFunc("POST /api/news/", createNewsItem)
	r.HandleFunc("GET /api/news/", readNewsItems)
	r.HandleFunc("GET /api/news/{id}", readNewsItem)
	r.HandleFunc("PATCH /api/news/", updateNewsItem)
	r.HandleFunc("DELETE /api/news/{id}", deleteNewsItem)

	r.HandleFunc("POST /api/retailers/", createRetailerItem)
	r.HandleFunc("GET /api/retailers/", readRetailerItems)
	r.HandleFunc("GET /api/retailers/{id}", readRetailerItem)
	r.HandleFunc("PATCH /api/retailers/", updateRetailerItem)
	r.HandleFunc("DELETE /api/retailers/{id}", deleteRetailerItem)
}

func handleError(err error, statusCode int, rw http.ResponseWriter) {
	slog.Warn("rest error", "error", err)
	rw.Header().Add("Content-Type", "application/json")
	rw.WriteHeader(statusCode)
	json.NewEncoder(rw).Encode(ErrorResponse{
		Status: http.StatusText(statusCode),
		Error:  err.Error(),
	})
}

func decode(r io.Reader, val any) error {
	dec := json.NewDecoder(r)
	dec.DisallowUnknownFields()
	return dec.Decode(val)
}
