package response

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

type Envelope struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data"`
}

type DetailEnvelope struct {
	Detail any `json:"detail"`
}

func OK(w http.ResponseWriter, data any) {
	Write(w, http.StatusOK, 200, "success", data)
}

func Error(w http.ResponseWriter, statusCode int, message string) {
	if message == "" {
		message = http.StatusText(statusCode)
	}
	Write(w, statusCode, statusCode, message, nil)
}

func Detail(w http.ResponseWriter, statusCode int, detail any) {
	if detail == nil || detail == "" {
		detail = http.StatusText(statusCode)
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(statusCode)
	_ = json.NewEncoder(w).Encode(DetailEnvelope{Detail: detail})
}

func Write(w http.ResponseWriter, statusCode int, code int, message string, data any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(statusCode)
	_ = json.NewEncoder(w).Encode(Envelope{
		Code:    code,
		Message: message,
		Data:    data,
	})
}
