package wallet

import (
	"context"
	"strconv"

	walletapp "github.com/break/junhong_cmp_fiber/internal/application/wallet"
	"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"gorm.io/gorm"
)

// RefundEventWriter 将代理主钱包退款事实写入公共 Outbox。
type RefundEventWriter struct {
	outbox *outbox.Repository
}

// NewRefundEventWriter 创建代理主钱包退款 Outbox Writer。
func NewRefundEventWriter(repository *outbox.Repository) *RefundEventWriter {
	return &RefundEventWriter{outbox: repository}
}

// Append 在调用方业务事务中追加代理主钱包退款事件。
func (w *RefundEventWriter) Append(ctx context.Context, tx *gorm.DB, event walletapp.RefundedEvent) error {
	if w == nil || w.outbox == nil {
		return errors.New(errors.CodeInternalError, "代理主钱包退款 Outbox Writer 未配置")
	}
	_, err := w.outbox.Append(ctx, tx, outbox.Envelope{
		EventID: event.EventID, EventType: constants.OutboxEventTypeAgentMainWalletRefunded,
		PayloadVersion: constants.AgentMainWalletRefundedPayloadVersionV1,
		AggregateType:  "agent_wallet", AggregateID: strconv.FormatUint(uint64(event.WalletID), 10),
		ResourceType: constants.ReferenceTypeRefund, ResourceID: strconv.FormatUint(uint64(event.RefundID), 10),
		BusinessKey: event.EventID, RequestID: event.RequestID, CorrelationID: event.CorrelationID, Payload: event,
	})
	return err
}
