package com.jeesharp.business.modules.pay.profitsharing.application.support;

import com.jeesharp.business.modules.pay.api.PayProfitSharingChannelApi;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.application.support.PaySubMerchantApplymentOperateSupport;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.entity.PaySubMerchantApplyment;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 进件完成后预注册微信分账接收方，与进件同步流程解耦。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Slf4j
@Component
@AllArgsConstructor
public class PayProfitSharingReceiverBootstrapSupport {

    private final PayProfitSharingChannelApi payProfitSharingChannelApi;

    /**
     * 进件 FINISH 且为有效二级商户时预注册分账接收方（失败不阻断调用方）。
     */
    public void bootstrapIfReady(PaySubMerchantApplyment applyment) {
        if (!PaySubMerchantApplymentOperateSupport.isEffectiveSubMerchant(applyment)) {
            return;
        }
        try {
            var result = payProfitSharingChannelApi.ensureSubMerchantSelfReceiver(null, applyment.getSubMchId());
            if (!Boolean.TRUE.equals(result.getSuccess())) {
                log.warn("进件 {} 预注册分账接收方失败 subMch={}: {}",
                        applyment.getId(), applyment.getSubMchId(), result.getErrorMsg());
            }
        } catch (Exception ex) {
            log.warn("进件 {} 预注册分账接收方异常 subMch={}: {}",
                    applyment.getId(), applyment.getSubMchId(), ex.getMessage());
        }
    }
}
