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

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jeesharp.business.modules.pay.config.weixin.PayWechatCredentialSupport;
import com.jeesharp.business.modules.pay.config.weixin.PayWechatWxPayClientHolder;
import com.jeesharp.business.modules.pay.core.IJPayHttpResponse;
import com.jeesharp.business.modules.pay.core.enums.RequestMethod;
import com.jeesharp.business.modules.pay.paychannelconfig.support.PayChannelTenantSupport;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.support.PayWechatInterfaceLogRecorder;
import com.jeesharp.business.modules.pay.weixin.support.PayWechatInterfaceLogScenario;
import com.jeesharp.business.modules.pay.paywechatconfig.entity.PayWechatConfig;
import com.jeesharp.business.modules.pay.wxpay.WxPayApi;
import com.jeesharp.business.modules.pay.wxpay.enums.WxApiType;
import com.jeesharp.business.modules.pay.wxpay.enums.WxDomain;
import com.jeesharp.framework.log.api.entity.InterfaceLogEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 微信支付 V3 资金余额查询客户端（平台服务商 / 电商收付通特约商户）。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class PayWechatFundClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatInterfaceLogRecorder interfaceLogRecorder;

    /**
     * 查询平台服务商自身账户余额。
     */
    public JSONObject queryPlatformBalance(String accountType, String configTenantId) throws Exception {
        PayWechatConfig config = requireConfig(configTenantId);
        String suffix = String.format(WxApiType.MERCHANT_FUND_BALANCE.getType(), accountType);
        return executeLogged(
                PayWechatInterfaceLogScenario.FUND_BALANCE_PLATFORM,
                suffix,
                null,
                accountType,
                configTenantId,
                "查询平台账户余额失败",
                () -> v3Get(config, suffix));
    }

    /**
     * 查询特约商户账户余额。
     */
    public JSONObject querySubMerchantBalance(String subMchId, String accountType, String configTenantId) throws Exception {
        PayWechatConfig config = requireConfig(configTenantId);
        String suffix = UriComponentsBuilder.fromPath(String.format(WxApiType.QUERY_BALANCE.getType(), subMchId))
                .queryParam("account_type", accountType)
                .build()
                .toUriString();
        return executeLogged(
                PayWechatInterfaceLogScenario.FUND_BALANCE_MERCHANT,
                suffix,
                null,
                subMchId + ":" + accountType,
                configTenantId,
                "查询特约商户账户余额失败",
                () -> v3Get(config, suffix));
    }

    public PayWechatConfig requireConfig(String configTenantId) {
        String tenantId = StrUtil.blankToDefault(configTenantId, PayChannelTenantSupport.PLATFORM_TENANT_ID);
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        if (!PayWechatCredentialSupport.isWxEnabled(config)) {
            throw new IllegalStateException("请先在【支付 · 微信配置】中启用「调用真实微信 V3」");
        }
        if (!StringUtils.hasText(config.getCertPrivateKeyPath())) {
            throw new IllegalStateException("余额查询需配置商户 API 私钥路径 certPrivateKeyPath");
        }
        return config;
    }

    private JSONObject executeLogged(
            String scenarioType,
            String urlSuffix,
            String requestParam,
            String businessId,
            String tenantId,
            String action,
            V3Call call) throws Exception {
        String requestUrl = WxDomain.CHINA.getType() + urlSuffix;
        long startMs = System.currentTimeMillis();
        InterfaceLogEntity logEntity = interfaceLogRecorder.begin(
                scenarioType, RequestMethod.GET.name(), requestUrl, requestParam, businessId,
                "configTenantId=" + StrUtil.blankToDefault(tenantId, ""));
        try {
            IJPayHttpResponse response = call.execute();
            int status = response != null ? response.getStatus() : 0;
            if (status >= 200 && status < 300) {
                interfaceLogRecorder.completeSuccess(logEntity, response, startMs);
            } else {
                interfaceLogRecorder.completeHttpFail(logEntity, response, startMs, buildHttpErrorMessage(response, action));
            }
            JSONObject result = parseResponse(response, action);
            interfaceLogRecorder.saveAsync(logEntity);
            return result;
        } catch (Exception e) {
            interfaceLogRecorder.completeError(logEntity, startMs, e.getMessage());
            interfaceLogRecorder.saveAsync(logEntity);
            throw e;
        }
    }

    private static String buildHttpErrorMessage(IJPayHttpResponse response, String action) {
        if (response == null) {
            return action + "：无响应";
        }
        String body = response.getBody();
        if (StringUtils.hasText(body) && JSONUtil.isTypeJSON(body)) {
            JSONObject err = JSONUtil.parseObj(body);
            String msg = err.getStr("message", body);
            if (err.containsKey("code")) {
                return err.getStr("code") + ": " + msg;
            }
            return msg;
        }
        return action + "（HTTP " + response.getStatus() + "）";
    }

    private IJPayHttpResponse v3Get(PayWechatConfig config, String urlSuffix) throws Exception {
        return WxPayApi.v3(RequestMethod.GET, WxDomain.CHINA.getType(), urlSuffix,
                config.getMchId(),
                PayWechatCredentialSupport.resolveMerchantSerialNo(config),
                config.getPublicKeyId(),
                config.getCertPrivateKeyPath().trim(),
                "");
    }

    private static JSONObject parseResponse(IJPayHttpResponse response, String action) {
        if (response == null) {
            throw new IllegalStateException(action + "：无响应");
        }
        int status = response.getStatus();
        String body = response.getBody();
        if (status >= 200 && status < 300) {
            return StringUtils.hasText(body) ? JSONUtil.parseObj(body) : new JSONObject();
        }
        String msg = body;
        if (StringUtils.hasText(body) && JSONUtil.isTypeJSON(body)) {
            JSONObject err = JSONUtil.parseObj(body);
            msg = err.getStr("message", body);
            if (err.containsKey("code")) {
                msg = err.getStr("code") + ": " + msg;
            }
        }
        throw new IllegalStateException(action + "（HTTP " + status + "）：" + msg);
    }

    @FunctionalInterface
    private interface V3Call {
        IJPayHttpResponse execute() throws Exception;
    }
}
