package com.jeesharp.business.modules.pay.direct.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.dto.PayWechatTransactionOpsResultDTO;
import com.jeesharp.business.modules.pay.paychannelconfig.support.PayChannelTenantSupport;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.support.PayWechatInterfaceLogRecorder;
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;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 微信境内直连 V3 查单/关单客户端（/v3/pay/transactions/*）。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class PayWechatDirectTransactionClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatInterfaceLogRecorder interfaceLogRecorder;

    public PayWechatTransactionOpsResultDTO queryByOutTradeNo(String platformTenantId, String outTradeNo) {
        try {
            PayWechatConfig config = resolveConfig(platformTenantId);
            String suffix = UriComponentsBuilder.fromPath(String.format(WxApiType.ORDER_QUERY_BY_NO.getType(), outTradeNo))
                    .queryParam("mchid", config.getMchId())
                    .build()
                    .toUriString();
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.DIRECT_TRANSACTIONS_QUERY,
                    RequestMethod.GET,
                    suffix,
                    null,
                    outTradeNo,
                    platformTenantId,
                    "直连查单失败",
                    config);
            PayWechatTransactionOpsResultDTO result = new PayWechatTransactionOpsResultDTO();
            result.setTradeState(wxResp.getStr("trade_state"));
            result.setSuccess(true);
            result.setRawResponse(wxResp.toString());
            return result;
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    public PayWechatTransactionOpsResultDTO close(String platformTenantId, String outTradeNo) {
        try {
            PayWechatConfig config = resolveConfig(platformTenantId);
            JSONObject body = new JSONObject();
            body.set("mchid", config.getMchId());
            String suffix = String.format(WxApiType.CLOSE_ORDER_BY_NO.getType(), outTradeNo);
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.DIRECT_TRANSACTIONS_CLOSE,
                    RequestMethod.POST,
                    suffix,
                    body.toString(),
                    outTradeNo,
                    platformTenantId,
                    "直连关单失败",
                    config);
            PayWechatTransactionOpsResultDTO result = new PayWechatTransactionOpsResultDTO();
            result.setSuccess(true);
            result.setRawResponse(JSONUtil.createObj().set("request", body).set("response", wxResp).toString());
            return result;
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    private PayWechatConfig resolveConfig(String platformTenantId) {
        String tenantId = StrUtil.blankToDefault(platformTenantId, PayChannelTenantSupport.PLATFORM_TENANT_ID);
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        if (!PayWechatCredentialSupport.isWxEnabled(config)) {
            throw new IllegalStateException("未启用真实微信 V3：请在后台开启「调用真实微信」");
        }
        return config;
    }

    private JSONObject executeLogged(
            String scenarioType,
            RequestMethod method,
            String urlSuffix,
            String requestBody,
            String businessId,
            String tenantId,
            String action,
            PayWechatConfig config) throws Exception {
        String requestUrl = WxDomain.CHINA.getType() + urlSuffix;
        long startMs = System.currentTimeMillis();
        InterfaceLogEntity logEntity = interfaceLogRecorder.begin(
                scenarioType, method.name(), requestUrl, requestBody, businessId,
                "configTenantId=" + StrUtil.blankToDefault(tenantId, ""));
        try {
            IJPayHttpResponse response = method == RequestMethod.GET
                    ? v3Get(config, urlSuffix)
                    : v3Post(config, urlSuffix, StrUtil.blankToDefault(requestBody, ""));
            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 PayWechatTransactionOpsResultDTO fail(String message) {
        PayWechatTransactionOpsResultDTO result = new PayWechatTransactionOpsResultDTO();
        result.setSuccess(false);
        result.setErrorMsg(message);
        return result;
    }

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