package com.starry.admin.modules.order.listener;

import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomUserInfoService;
import com.starry.admin.modules.order.module.constant.OrderConstant.BalanceOperationType;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.module.event.OrderRevocationEvent;
import java.math.BigDecimal;
import java.util.Optional;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
public class OrderRevocationBalanceListener {

    private final IPlayCustomUserInfoService customUserInfoService;

    public OrderRevocationBalanceListener(IPlayCustomUserInfoService customUserInfoService) {
        this.customUserInfoService = customUserInfoService;
    }

    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void handle(OrderRevocationEvent event) {
        if (event == null || event.getContext() == null || event.getOrderSnapshot() == null) {
            return;
        }
        if (!event.getContext().isRefundToCustomer()) {
            return;
        }

        BigDecimal refundAmount = Optional.ofNullable(event.getContext().getRefundAmount()).orElse(BigDecimal.ZERO);
        if (refundAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        PlayOrderInfoEntity order = event.getOrderSnapshot();
        PlayCustomUserInfoEntity customer = customUserInfoService.getById(order.getPurchaserBy());
        if (customer == null) {
            throw new CustomException("顾客信息不存在");
        }
        BigDecimal currentBalance = Optional.ofNullable(customer.getAccountBalance()).orElse(BigDecimal.ZERO);
        customUserInfoService.updateAccountBalanceById(
                customer.getId(),
                currentBalance,
                currentBalance.add(refundAmount),
                BalanceOperationType.REFUND.getCode(),
                "已完成订单撤销退款",
                refundAmount,
                BigDecimal.ZERO,
                order.getId());
    }
}
