package com.jeesharp.business.modules.finance.payrefund.application;

import com.jeesharp.business.modules.finance.api.ProfitSharingReturnApi;
import com.jeesharp.business.modules.finance.merchantsettle.enums.SettleModeEnum;
import com.jeesharp.business.modules.finance.payorder.entity.PayOrder;
import com.jeesharp.business.modules.finance.payrefund.entity.PayRefundOrder;
import com.jeesharp.business.modules.finance.profitsharing.entity.ProfitSharingOrder;
import com.jeesharp.business.modules.finance.profitsharing.enums.ProfitSharingStatusEnum;
import com.jeesharp.business.modules.finance.profitsharing.service.ProfitSharingOrderService;
import com.jeesharp.framework.exception.BizErrorException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 退款前结算编排：按 settle_mode 与分账状态决定取消待分账、分账回退或直接退款。
 *
 * @author jeesharp
 * @since 2026-06-11
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class RefundSettleOrchestrator {

    private final ProfitSharingOrderService profitSharingOrderService;
    private final ProfitSharingReturnApi profitSharingReturnApi;

    /**
     * 微信退款前准备：场景 B 无额外步骤；场景 C 按分账状态取消或回退。
     */
    @Transactional(readOnly = false)
    public void prepareBeforeWechatRefund(PayRefundOrder refund, PayOrder payOrder) {
        if (refund == null || payOrder == null) {
            return;
        }
        if (!SettleModeEnum.WECHAT_PROFIT_SHARING.getValue().equals(payOrder.getSettleMode())) {
            profitSharingOrderService.cancelSharingForRefund(refund.getMallOrderId(), false);
            return;
        }
        ProfitSharingOrder sharing = profitSharingOrderService.findByMallOrderId(refund.getMallOrderId());
        if (sharing == null) {
            return;
        }
        String status = sharing.getStatus();
        if (ProfitSharingStatusEnum.PENDING.getValue().equals(status)
                || ProfitSharingStatusEnum.FAIL.getValue().equals(status)) {
            profitSharingOrderService.cancelSharingForRefund(refund.getMallOrderId(), true);
            return;
        }
        if (ProfitSharingStatusEnum.PROCESSING.getValue().equals(status)) {
            throw new BizErrorException("子单分账处理中，请稍后重试退款");
        }
        if (ProfitSharingStatusEnum.SUCCESS.getValue().equals(status)
                || ProfitSharingStatusEnum.FINISHED.getValue().equals(status)) {
            boolean ready = profitSharingReturnApi.ensureReturnForRefund(refund.getId());
            if (!ready) {
                throw new BizErrorException("分账回退处理中，请稍后重试退款");
            }
            return;
        }
        if (ProfitSharingStatusEnum.CANCELLED.getValue().equals(status)) {
            return;
        }
    }
}
