// Package messagemq defines RocketMQ payloads owned by activity-service message modules.
package messagemq

import (
	"encoding/json"
	"errors"
	"strings"
)

const (
	MessageTypeActionOutboxEvent = "message_action_outbox_event"

	TagMessageActionOutboxEvent = "message_action_outbox_event"
)

// ActionOutboxMessage is the MQ representation of one committed message_action_outbox fact.
type ActionOutboxMessage struct {
	MessageType  string `json:"message_type"`
	AppCode      string `json:"app_code"`
	EventID      string `json:"event_id"`
	EventType    string `json:"event_type"`
	ConfirmID    string `json:"confirm_id"`
	PayloadJSON  string `json:"payload_json"`
	OccurredAtMS int64  `json:"occurred_at_ms"`
}

// EncodeActionOutboxMessage serializes a confirm-message fact for notice-service delivery.
func EncodeActionOutboxMessage(message ActionOutboxMessage) ([]byte, error) {
	message.MessageType = MessageTypeActionOutboxEvent
	if strings.TrimSpace(message.AppCode) == "" ||
		strings.TrimSpace(message.EventID) == "" ||
		strings.TrimSpace(message.EventType) == "" ||
		strings.TrimSpace(message.ConfirmID) == "" ||
		message.OccurredAtMS <= 0 {
		return nil, errors.New("message action outbox message is incomplete")
	}
	if strings.TrimSpace(message.PayloadJSON) == "" {
		message.PayloadJSON = "{}"
	}
	return json.Marshal(message)
}

// DecodeActionOutboxMessage validates one confirm-message MQ body.
func DecodeActionOutboxMessage(body []byte) (ActionOutboxMessage, error) {
	var message ActionOutboxMessage
	if err := json.Unmarshal(body, &message); err != nil {
		return ActionOutboxMessage{}, err
	}
	if message.MessageType != MessageTypeActionOutboxEvent {
		return ActionOutboxMessage{}, errors.New("unexpected message action outbox message_type")
	}
	if strings.TrimSpace(message.AppCode) == "" ||
		strings.TrimSpace(message.EventID) == "" ||
		strings.TrimSpace(message.EventType) == "" ||
		strings.TrimSpace(message.ConfirmID) == "" ||
		message.OccurredAtMS <= 0 {
		return ActionOutboxMessage{}, errors.New("message action outbox message is incomplete")
	}
	if strings.TrimSpace(message.PayloadJSON) == "" {
		message.PayloadJSON = "{}"
	}
	return message, nil
}
