package approval

import (
	"context"
	"strconv"

	"github.com/bytedance/sonic"
	"gorm.io/gorm"

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

// TerminalEventWriter 将通用审批标准决策写入公共 Outbox。
type TerminalEventWriter struct {
	outbox *outbox.Repository
}

// NewTerminalEventWriter 创建通用审批标准决策 Outbox Writer。
func NewTerminalEventWriter(repository *outbox.Repository) *TerminalEventWriter {
	return &TerminalEventWriter{outbox: repository}
}

// Append 在审批状态事务中追加结构化标准决策事件。
func (w *TerminalEventWriter) Append(ctx context.Context, tx *gorm.DB, event approvalapp.TerminalDecisionEvent) 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.OutboxEventTypeApprovalTerminalDecision,
		PayloadVersion: constants.ApprovalTerminalDecisionPayloadVersionV1,
		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
}

// TerminalDecisionConsumer 将公共 Outbox 信封转换为渠道无关业务决策。
type TerminalDecisionConsumer struct {
	dispatcher *approvalapp.DecisionDispatcher
}

// NewTerminalDecisionConsumer 创建审批标准决策消费者 Adapter。
func NewTerminalDecisionConsumer(dispatcher *approvalapp.DecisionDispatcher) *TerminalDecisionConsumer {
	return &TerminalDecisionConsumer{dispatcher: dispatcher}
}

// Consume 校验事件类型、版本和稳定身份后交给业务分发器。
func (c *TerminalDecisionConsumer) Consume(ctx context.Context, envelope outbox.DeliveryEnvelope) error {
	if c == nil || c.dispatcher == nil {
		return errors.New(errors.CodeInternalError, "审批标准决策消费者未配置")
	}
	if envelope.EventType != constants.OutboxEventTypeApprovalTerminalDecision ||
		envelope.PayloadVersion != constants.ApprovalTerminalDecisionPayloadVersionV1 {
		return errors.New(errors.CodeInvalidParam, "审批标准决策事件类型或版本不受支持")
	}
	var event approvalapp.TerminalDecisionEvent
	if err := sonic.Unmarshal(envelope.Payload, &event); err != nil {
		return errors.Wrap(errors.CodeInvalidParam, err, "审批标准决策事件载荷格式错误")
	}
	if event.EventID == "" || event.EventID != envelope.EventID || event.InstanceID == 0 ||
		event.BusinessType == "" || event.BusinessID == 0 || event.CorrelationID == "" {
		return errors.New(errors.CodeInvalidParam, "审批标准决策事件载荷不完整")
	}
	if _, err := approvaldomain.StatusForDecision(event.Decision); err != nil {
		return err
	}
	return c.dispatcher.Consume(ctx, event)
}
