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"
)

// ReservationEventWriter 将代理主钱包预占状态写入公共 Outbox。
type ReservationEventWriter struct {
	outbox *outbox.Repository
}

// NewReservationEventWriter 创建代理主钱包预占 Outbox Writer。
func NewReservationEventWriter(repository *outbox.Repository) *ReservationEventWriter {
	return &ReservationEventWriter{outbox: repository}
}

// Append 在调用方事务中追加预占状态事件。
func (w *ReservationEventWriter) Append(ctx context.Context, tx *gorm.DB, event walletapp.ReservationEvent) 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.OutboxEventTypeAgentMainWalletReservationChanged,
		PayloadVersion: constants.AgentMainWalletReservationPayloadVersionV1,
		AggregateType:  "agent_wallet_reservation", AggregateID: strconv.FormatUint(uint64(event.ReservationID), 10),
		ResourceType: event.ReferenceType, ResourceID: strconv.FormatUint(uint64(event.ReferenceID), 10),
		BusinessKey: event.EventID, RequestID: event.RequestID, CorrelationID: event.CorrelationID, Payload: event,
	})
	return err
}
