package com.jeesharp.business.modules.pay.payalipayconfig.config;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.jeesharp.business.modules.pay.payalipayconfig.entity.PayAlipayConfig;
import com.jeesharp.business.modules.pay.payalipayconfig.service.PayAlipayConfigService;
import com.jeesharp.business.modules.pay.payalipayconfig.support.PayAlipayCredentialSupport;
import com.jeesharp.business.modules.pay.paytype.alipay.AliPayApiConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 按租户解析 {@link pay_alipay_config} 并构建支付宝 SDK 客户端。
 *
 * @author jeesharp
 * @since 2026-05-25
 */
@Component
@RequiredArgsConstructor
public class PayAlipayClientHolder {

    private final PayAlipayConfigService payAlipayConfigService;

    public PayAlipayConfig findActiveConfig(String tenantId) {
        return payAlipayConfigService.findActive(tenantId);
    }

    public PayAlipayConfig requireActiveConfig(String tenantId) {
        PayAlipayConfig config = findActiveConfig(tenantId);
        if (config == null) {
            throw new IllegalStateException("未配置支付宝：请在管理后台【支付 · 支付宝配置】保存并启用");
        }
        return config;
    }

    public AliPayApiConfig buildApiConfig(PayAlipayConfig config) throws AlipayApiException {
        AliPayApiConfig api = AliPayApiConfig.builder()
                .setAppId(config.getAppId())
                .setPrivateKey(config.getPrivateKey())
                .setAliPayPublicKey(config.getAliPayPublicKey())
                .setServiceUrl(StrUtil.blankToDefault(config.getServiceUrl(),
                        "https://openapi.alipay.com/gateway.do"))
                .setCharset(StrUtil.blankToDefault(config.getCharset(), "UTF-8"))
                .setSignType(StrUtil.blankToDefault(config.getSignType(), "RSA2"))
                .setCertModel(PayAlipayCredentialSupport.isCertModel(config));
        if (PayAlipayCredentialSupport.isCertModel(config)) {
            return api.setAppCertPath(config.getAppCertPath())
                    .setAliPayCertPath(config.getAliPayCertPath())
                    .setAliPayRootCertPath(config.getAliPayRootCertPath())
                    .buildByCert();
        }
        return api.build();
    }

    public AlipayClient requireClient(String tenantId) throws AlipayApiException {
        PayAlipayConfig config = requireActiveConfig(tenantId);
        if (!PayAlipayCredentialSupport.isAliEnabled(config)) {
            throw new IllegalStateException("未启用真实支付宝下单");
        }
        return buildApiConfig(config).getAliPayClient();
    }

    public String resolveNotifyUrl(PayAlipayConfig config) {
        if (config == null) {
            return null;
        }
        String base = StrUtil.blankToDefault(config.getNotifyBaseUrl(), "");
        String path = StrUtil.blankToDefault(config.getPayCenterNotifyPath(), "/api/pay/payNotify/aliPayNotify");
        if (base.isEmpty()) {
            return path.startsWith("http") ? path : null;
        }
        return base.replaceAll("/+$", "") + (path.startsWith("/") ? path : "/" + path);
    }
}
