package approval

import (
	"context"
	"strconv"

	"gorm.io/gorm"

	approvalapp "github.com/break/junhong_cmp_fiber/internal/application/approval"
	"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"
)

// SubmissionEventWriter 将通用审批申请写入公共 Outbox。
type SubmissionEventWriter struct {
	outbox *outbox.Repository
}

// NewSubmissionEventWriter 创建通用审批申请 Outbox Writer。
func NewSubmissionEventWriter(repository *outbox.Repository) *SubmissionEventWriter {
	return &SubmissionEventWriter{outbox: repository}
}

// Append 在调用方业务事务中追加渠道提交事件。
func (w *SubmissionEventWriter) Append(ctx context.Context, tx *gorm.DB, event approvalapp.SubmissionRequestedEvent) 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.OutboxEventTypeApprovalSubmissionRequested,
		PayloadVersion: constants.ApprovalSubmissionPayloadVersionV1,
		AggregateType:  "approval", AggregateID: strconv.FormatUint(uint64(event.InstanceID), 10),
		ResourceType: event.BusinessType, ResourceID: strconv.FormatUint(uint64(event.BusinessID), 10),
		BusinessKey: event.EventID, CorrelationID: event.CorrelationID, Payload: event,
	})
	return err
}
