package utils

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

	"github.com/calendarapi/internal/models"
)

func WriteJSON(w http.ResponseWriter, status int, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(data)
}

func WriteError(w http.ResponseWriter, err error) {
	if appErr, ok := models.IsAppError(err); ok {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(appErr.Status)
		json.NewEncoder(w).Encode(appErr)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusInternalServerError)
	json.NewEncoder(w).Encode(models.ErrInternal)
}

func WriteOK(w http.ResponseWriter) {
	WriteJSON(w, http.StatusOK, map[string]bool{"ok": true})
}

func WriteList(w http.ResponseWriter, items interface{}, page models.PageInfo) {
	WriteJSON(w, http.StatusOK, models.ListResponse{Items: items, Page: page})
}

func DecodeJSON(r *http.Request, dst interface{}) error {
	if r.Body == nil {
		return models.NewValidationError("request body required")
	}
	if err := json.NewDecoder(r.Body).Decode(dst); err != nil {
		return models.NewValidationError("invalid JSON: " + err.Error())
	}
	return nil
}
