package com.jeesharp.business.modules.pay.route.support;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.pay.paychannelconfig.support.PayChannelTenantSupport;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.entity.PaySubMerchantApplyment;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.service.PaySubMerchantApplymentService;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.support.PaySubMerchantApplyStatusSupport;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 预下单路由：按商户租户解析有效 sub_mchid。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class PayWechatSubMerchantRouteSupport {

    private final PaySubMerchantApplymentService paySubMerchantApplymentService;

    public String resolveSubMchId(String merchantTenantId) {
        PaySubMerchantApplyment applyment = findEffectiveApplyment(merchantTenantId);
        return applyment == null ? null : StrUtil.trimToNull(applyment.getSubMchId());
    }

    public String requireSubMchId(String merchantTenantId) {
        String subMchId = resolveSubMchId(merchantTenantId);
        if (StrUtil.isBlank(subMchId)) {
            throw new IllegalStateException("商户未完成微信进件或 sub_mch_id 无效，tenantId=" + merchantTenantId);
        }
        return subMchId;
    }

    private PaySubMerchantApplyment findEffectiveApplyment(String merchantTenantId) {
        if (StrUtil.isBlank(merchantTenantId)) {
            return null;
        }
        String storageTenantId = PayChannelTenantSupport.toStorageKey(merchantTenantId.trim());
        PaySubMerchantApplyment applyment = paySubMerchantApplymentService.findByApplymentTenantId(storageTenantId);
        return PaySubMerchantApplyStatusSupport.isEffectiveSubMerchant(applyment) ? applyment : null;
    }
}
