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

import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.v3.util.PemUtils;
import com.jeesharp.business.modules.pay.config.weixin.PayWechatCredentialSupport;
import com.jeesharp.business.modules.pay.paywechatconfig.entity.PayWechatConfig;
import lombok.experimental.UtilityClass;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

/**
 * 将 partner/合单返回的 prepay_id 签名为小程序调起参数。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@UtilityClass
public class PayWechatJsapiSignSupport {

    public static WxPayUnifiedOrderV3Result.JsapiResult signJsapi(PayWechatConfig config, String prepayId) throws Exception {
        if (StrUtil.isBlank(prepayId)) {
            throw new IllegalStateException("prepay_id 为空，无法签名调起参数");
        }
        String pemBody = PayWechatCredentialSupport.resolveMerchantPrivateKeyPem(config);
        String appId = config.getAppId();
        String mchId = config.getMchId();
        try (ByteArrayInputStream in = new ByteArrayInputStream(pemBody.getBytes(StandardCharsets.UTF_8))) {
            PrivateKey merchantPrivateKey = PemUtils.loadPrivateKey(in);
            WxPayUnifiedOrderV3Result stub = new WxPayUnifiedOrderV3Result();
            stub.setPrepayId(prepayId);
            return stub.getPayInfo(TradeTypeEnum.JSAPI, appId, mchId, merchantPrivateKey);
        }
    }
}
