package app

import (
	"encoding/json"

	"hyapp/pkg/appcode"
	"hyapp/pkg/usermq"
	inviteactivitydomain "hyapp/services/activity-service/internal/domain/inviteactivity"
)

func inviteActivityValidInviteEventFromUserMessage(body []byte) (inviteactivitydomain.ValidInviteEvent, bool, error) {
	message, err := usermq.DecodeUserOutboxMessage(body)
	if err != nil {
		return inviteactivitydomain.ValidInviteEvent{}, false, err
	}
	if message.EventType != inviteactivitydomain.EventTypeUserInviteBecameValid {
		return inviteactivitydomain.ValidInviteEvent{}, false, nil
	}
	var decoded map[string]any
	if err := json.Unmarshal([]byte(message.PayloadJSON), &decoded); err != nil || decoded == nil {
		decoded = map[string]any{}
	}
	invitedUserID := firstNonZeroInt64(int64FromDecoded(decoded, "invited_user_id"), message.AggregateID)
	inviterUserID := int64FromDecoded(decoded, "inviter_user_id")
	if invitedUserID <= 0 || inviterUserID <= 0 {
		return inviteactivitydomain.ValidInviteEvent{}, false, nil
	}
	return inviteactivitydomain.ValidInviteEvent{
		AppCode:       appcode.Normalize(message.AppCode),
		EventID:       message.EventID,
		EventType:     message.EventType,
		InviterUserID: inviterUserID,
		InvitedUserID: invitedUserID,
		PayloadJSON:   message.PayloadJSON,
		OccurredAtMS:  message.OccurredAtMS,
	}, true, nil
}

func inviteActivityInviteEventFromUserMessage(body []byte) (inviteactivitydomain.InviteEvent, bool, error) {
	message, err := usermq.DecodeUserOutboxMessage(body)
	if err != nil {
		return inviteactivitydomain.InviteEvent{}, false, err
	}
	if message.EventType != inviteactivitydomain.EventTypeUserInvited {
		return inviteactivitydomain.InviteEvent{}, false, nil
	}
	var decoded map[string]any
	if err := json.Unmarshal([]byte(message.PayloadJSON), &decoded); err != nil || decoded == nil {
		decoded = map[string]any{}
	}
	invitedUserID := firstNonZeroInt64(int64FromDecoded(decoded, "invited_user_id"), message.AggregateID)
	inviterUserID := int64FromDecoded(decoded, "inviter_user_id")
	if invitedUserID <= 0 || inviterUserID <= 0 {
		return inviteactivitydomain.InviteEvent{}, false, nil
	}
	return inviteactivitydomain.InviteEvent{
		AppCode:       appcode.Normalize(message.AppCode),
		EventID:       message.EventID,
		EventType:     message.EventType,
		InviterUserID: inviterUserID,
		InvitedUserID: invitedUserID,
		InviteCode:    stringFromDecoded(decoded, "invite_code"),
		Source:        stringFromDecoded(decoded, "source"),
		PayloadJSON:   message.PayloadJSON,
		OccurredAtMS:  message.OccurredAtMS,
	}, true, nil
}
