package wrapper

import (
	"common/net/http/http_resp"
	"encoding/json"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"io"
)

// WrappedMarshaler 自动包装响应为 { code, message, data }
type WrappedMarshaler struct {
	inner runtime.Marshaler
}

func NewWrappedMarshaler(inner runtime.Marshaler) *WrappedMarshaler {
	return &WrappedMarshaler{inner: inner}
}

// Marshal 将 gRPC 响应包装成统一格式
func (w *WrappedMarshaler) Marshal(v interface{}) ([]byte, error) {
	dataBytes, err := w.inner.Marshal(v)
	if err != nil {
		return json.Marshal(http_resp.Error(http_resp.Failed))
	}
	return json.Marshal(http_resp.Success(json.RawMessage(dataBytes)))
}

func (w *WrappedMarshaler) Unmarshal(data []byte, v interface{}) error {
	return w.inner.Unmarshal(data, v)
}

func (w *WrappedMarshaler) NewDecoder(r io.Reader) runtime.Decoder {
	return w.inner.NewDecoder(r)
}

func (w *WrappedMarshaler) NewEncoder(wr io.Writer) runtime.Encoder {
	return w.inner.NewEncoder(wr)
}

func (w *WrappedMarshaler) ContentType(v interface{}) string {
	return "application/json"
}
