package wallet

import (
	"context"
	"math"

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

	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/internal/model"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
)

// RefundEventConsumer 校验已投递的代理主钱包退款事件具有对应权威资金流水。
type RefundEventConsumer struct {
	db *gorm.DB
}

// NewRefundEventConsumer 创建代理主钱包退款事件消费者。
func NewRefundEventConsumer(db *gorm.DB) *RefundEventConsumer {
	return &RefundEventConsumer{db: db}
}

// Consume 复核退款流水及正常订单的原扣款流水，拒绝确认未知或损坏事件。
func (c *RefundEventConsumer) Consume(ctx context.Context, envelope outbox.DeliveryEnvelope) error {
	if c == nil || c.db == nil {
		return errors.New(errors.CodeInternalError, "代理主钱包退款事件消费者未配置")
	}
	if envelope.EventType != constants.OutboxEventTypeAgentMainWalletRefunded ||
		envelope.PayloadVersion != constants.AgentMainWalletRefundedPayloadVersionV1 {
		return errors.New(errors.CodeInvalidParam, "代理主钱包退款事件类型或版本不受支持")
	}
	var event walletapp.RefundedEvent
	if err := sonic.Unmarshal(envelope.Payload, &event); err != nil {
		return errors.Wrap(errors.CodeInvalidParam, err, "代理主钱包退款事件载荷无法解析")
	}
	if event.EventID != envelope.EventID || event.WalletID == 0 || event.ShopID == 0 ||
		event.OrderID == 0 || event.RefundID == 0 || event.Amount <= 0 || event.Version <= 0 ||
		event.OriginalDeductAmount <= 0 || event.Amount > event.OriginalDeductAmount {
		return errors.New(errors.CodeInvalidParam, "代理主钱包退款事件载荷不完整")
	}
	if event.Legacy == (event.OriginalDebitTransactionID > 0) {
		return errors.New(errors.CodeInvalidParam, "代理主钱包退款事件原扣款标识不一致")
	}

	var refund model.AgentWalletTransaction
	err := c.db.WithContext(ctx).Unscoped().
		Where("agent_wallet_id = ? AND reference_type = ? AND reference_id = ? AND transaction_type = ? AND status = ?",
			event.WalletID, constants.ReferenceTypeRefund, event.RefundID, constants.AgentTransactionTypeRefund, constants.TransactionStatusSuccess).
		First(&refund).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.New(errors.CodeInternalError, "代理主钱包退款事件缺少权威资金流水")
		}
		return errors.Wrap(errors.CodeDatabaseError, err, "查询代理主钱包退款流水失败")
	}
	if refund.ShopID != event.ShopID || refund.Amount != event.Amount ||
		refund.BalanceBefore != event.BalanceBefore || refund.BalanceAfter != event.BalanceAfter ||
		!sameRefundUint(refund.RelatedShopID, event.RelatedShopID) ||
		!sameRefundString(refund.TransactionSubtype, event.TransactionSubtype) ||
		refund.AssetType != event.AssetType || refund.AssetID != event.AssetID || refund.AssetIdentifier != event.AssetIdentifier {
		return errors.New(errors.CodeInternalError, "代理主钱包退款事件与权威退款流水不一致")
	}
	if event.Legacy {
		return nil
	}

	var debit model.AgentWalletTransaction
	err = c.db.WithContext(ctx).Unscoped().
		Where("id = ? AND agent_wallet_id = ? AND reference_type = ? AND reference_id = ? AND transaction_type = ? AND status = ?",
			event.OriginalDebitTransactionID, event.WalletID, constants.ReferenceTypeOrder, event.OrderID,
			constants.AgentTransactionTypeDeduct, constants.TransactionStatusSuccess).
		First(&debit).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return errors.New(errors.CodeInternalError, "代理主钱包退款事件缺少原扣款流水")
		}
		return errors.Wrap(errors.CodeDatabaseError, err, "查询代理主钱包原扣款流水失败")
	}
	if debit.Amount >= 0 || debit.Amount == math.MinInt64 || event.OriginalDeductAmount != -debit.Amount ||
		!sameRefundUint(debit.RelatedShopID, event.RelatedShopID) ||
		!sameRefundString(debit.TransactionSubtype, event.TransactionSubtype) ||
		debit.AssetType != event.AssetType || debit.AssetID != event.AssetID || debit.AssetIdentifier != event.AssetIdentifier {
		return errors.New(errors.CodeInternalError, "代理主钱包退款事件与原扣款流水不一致")
	}
	return nil
}

func sameRefundUint(left, right *uint) bool {
	return (left == nil && right == nil) || (left != nil && right != nil && *left == *right)
}

func sameRefundString(left, right *string) bool {
	return (left == nil && right == nil) || (left != nil && right != nil && *left == *right)
}
