package prototool

import (
	"fmt"

	"google.golang.org/grpc/mem"
	"google.golang.org/protobuf/proto"
)

// Will be needed later.

//func MarshalProto(opts proto.MarshalOptions, v any) (mem.BufferSlice, error) {
//	m, ok := v.(proto.Message)
//	if !ok {
//		return nil, fmt.Errorf("unexpected message type: %T", v)
//	}
//	var retBuf mem.Buffer
//	size := opts.Size(m)
//	if mem.IsBelowBufferPoolingThreshold(size) {
//		buf, err := opts.Marshal(m)
//		if err != nil {
//			return nil, err
//		}
//		retBuf = mem.SliceBuffer(buf)
//	} else {
//		pool := mem.DefaultBufferPool()
//		buf := pool.Get(size)
//		if _, err := opts.MarshalAppend((*buf)[:0], m); err != nil {
//			pool.Put(buf)
//			return nil, err
//		}
//		retBuf = mem.NewBuffer(buf, pool)
//	}
//	return mem.BufferSlice{retBuf}, nil
//}

func UnmarshalProto(opts proto.UnmarshalOptions, data mem.BufferSlice, v any) error {
	m, ok := v.(proto.Message)
	if !ok {
		return fmt.Errorf("unexpected message type: %T", v)
	}

	buf := data.MaterializeToBuffer(mem.DefaultBufferPool())
	defer buf.Free()
	// This doesn't use buffer as there is no way at the moment.
	return opts.Unmarshal(buf.ReadOnlyData(), m)
}
