package response

import (
	"github.com/goccy/go-json"
	"net/http"
)

type Response struct {
	Status  string      `json:"status"`
	Message *string     `json:"message"`
	Data    interface{} `json:"data"`
}

const (
	StatusOK    = "Success"
	StatusError = "Error"
)

func WriteJSON(w http.ResponseWriter, message *string, code int, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)

	statusText := StatusOK
	if code >= 400 {
		statusText = StatusError
	}

	if err := json.NewEncoder(w).Encode(&Response{Status: statusText, Message: message, Data: data}); err != nil {
		http.Error(w, "unknown error", http.StatusInternalServerError)
	}
}

func Error(w http.ResponseWriter, err error, code int) {
	errorMessage := err.Error()
	WriteJSON(w, &errorMessage, code, nil)
}
