package com.jeesharp.business.modules.pay.paysubmerchantapplyment.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.paywechatconfig.entity.PayWechatConfig;
import com.jeesharp.business.modules.pay.weixin.support.PayWechatInterfaceLogScenario;
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;

/**
 * 微信支付平台收付通电商进件 V3 接口客户端（{@code /v3/ecommerce/applyments/*}）。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class PayWechatEcommerceApplymentClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatInterfaceLogRecorder interfaceLogRecorder;

    /**
     * 提交电商进件申请 POST /v3/ecommerce/applyments/
     */
    public JSONObject submitApplyment(String requestJson, String tenantId) throws Exception {
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        ensureWxReady(config);
        String body = PayWechatApplymentCryptoSupport.encryptEcommerceSensitiveFields(requestJson, config);
        String suffix = WxApiType.E_COMMERCE_APPLY.getType();
        String businessId = extractOutRequestNo(requestJson);
        return executeLogged(
                PayWechatInterfaceLogScenario.APPLYMENT_ECOMMERCE_SUBMIT,
                RequestMethod.POST.name(),
                suffix,
                body,
                businessId,
                tenantId,
                "提交电商进件失败",
                () -> v3Post(config, suffix, body));
    }

    /**
     * 按业务申请编号（out_request_no）查询状态。
     */
    public JSONObject queryByOutRequestNo(String outRequestNo, String tenantId) throws Exception {
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        ensureWxReady(config);
        String suffix = String.format(WxApiType.E_COMMERCE_APPLY_STATE_BY_NO.getType(), outRequestNo);
        return executeLogged(
                PayWechatInterfaceLogScenario.APPLYMENT_ECOMMERCE_QUERY_BY_OUT_NO,
                RequestMethod.GET.name(),
                suffix,
                null,
                outRequestNo,
                tenantId,
                "查询电商进件状态失败",
                () -> v3Get(config, suffix));
    }

    /**
     * 按申请单号查询状态。
     */
    public JSONObject queryByApplymentId(Long applymentId, String tenantId) throws Exception {
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        ensureWxReady(config);
        String suffix = String.format(WxApiType.E_COMMERCE_APPLY_STATE.getType(), applymentId);
        return executeLogged(
                PayWechatInterfaceLogScenario.APPLYMENT_ECOMMERCE_QUERY_BY_ID,
                RequestMethod.GET.name(),
                suffix,
                null,
                String.valueOf(applymentId),
                tenantId,
                "查询电商进件状态失败",
                () -> v3Get(config, suffix));
    }

    private JSONObject executeLogged(
            String scenarioType,
            String httpMethod,
            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, httpMethod, requestUrl, requestParam, businessId, "applymentTenantId=" + 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 static String extractOutRequestNo(String requestJson) {
        if (!StringUtils.hasText(requestJson) || !JSONUtil.isTypeJSON(requestJson)) {
            return null;
        }
        try {
            return JSONUtil.parseObj(requestJson).getStr("out_request_no");
        } catch (Exception ignored) {
            return null;
        }
    }

    private static void ensureWxReady(PayWechatConfig config) {
        if (!PayWechatCredentialSupport.isWxEnabled(config)) {
            throw new IllegalStateException("请先在【支付 · 微信配置】中启用「调用真实微信 V3」");
        }
        if (!StringUtils.hasText(config.getPublicKeyId())) {
            throw new IllegalStateException("进件需配置微信支付公钥 ID（publicKeyId）用于敏感字段加密");
        }
        if (!StringUtils.hasText(PayWechatCredentialSupport.resolveWechatPayPublicKeyPem(config))) {
            throw new IllegalStateException("进件需配置微信支付公钥 PEM 或路径");
        }
        if (!StringUtils.hasText(config.getCertPrivateKeyPath())) {
            throw new IllegalStateException("进件需配置商户 API 私钥路径 certPrivateKeyPath");
        }
    }

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

    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;
    }
}
