package watermillmsg

import (
	"context"
	"encoding/json"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
)

type JSONMarshaler struct {
	NewUUID func() string
}

func (m JSONMarshaler) Marshal(ctx context.Context, v any) (*message.Message, error) {
	b, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}

	msg := message.NewMessage(m.newUUID(), b)
	msg.SetContext(ctx)
	msg.Metadata.Set("Content-Type", "application/json")

	return msg, nil
}

func (m JSONMarshaler) newUUID() string {
	if m.NewUUID != nil {
		return m.NewUUID()
	}
	return watermill.NewUUID()
}

func (m JSONMarshaler) Unmarshal(msg *message.Message, v any) error {
	return json.Unmarshal(msg.Payload, v)
}
