package mysql

import (
	"context"
	"fmt"
	"time"
)

func resourceOutboxEvent(eventType string, commandID string, userID int64, resourceID int64, payload any, nowMs int64) walletOutboxEvent {
	eventKey := fmt.Sprintf("%s|%s|%d|%d", eventType, commandID, userID, resourceID)
	return walletOutboxEvent{
		EventID:       "wev_" + stableHash(eventKey),
		EventType:     eventType,
		TransactionID: "",
		CommandID:     commandID,
		UserID:        userID,
		AssetType:     resourceOutboxAsset,
		Payload:       payload,
		CreatedAtMS:   nowMs,
	}
}

func (r *Repository) insertResourceOutboxNoTx(ctx context.Context, eventType string, commandID string, userID int64, resourceID int64, payload any) error {
	tx, err := r.db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer func() { _ = tx.Rollback() }()
	nowMs := time.Now().UnixMilli()
	if err := r.insertWalletOutbox(ctx, tx, []walletOutboxEvent{resourceOutboxEvent(eventType, commandID, userID, resourceID, payload, nowMs)}); err != nil {
		return err
	}
	return tx.Commit()
}
