package com.jeesharp.business.modules.pay.service.weixin;

import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.jeesharp.business.modules.pay.config.weixin.PayWechatCredentialSupport;
import com.jeesharp.business.modules.pay.config.weixin.PayWechatWxPayClientHolder;
import com.jeesharp.business.modules.pay.dto.BasicPayOrderData;
import com.jeesharp.business.modules.pay.dto.PayWechatPrepayRouteSnapshotDTO;
import com.jeesharp.business.modules.pay.paywechatconfig.entity.PayWechatConfig;
import com.jeesharp.business.modules.pay.route.PayWechatPayRouteResult;
import com.jeesharp.business.modules.pay.route.PayWechatPayRouter;
import com.jeesharp.business.modules.pay.vo.WechatJsapiPrepayVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 杏花村链路：微信 JSAPI V3 统一下单（经 {@link PayWechatPayRouter} 路由 Direct/Partner/Combine）。
 *
 * @author jeesharp
 * @since 2026-05-25
 */
@Service
@RequiredArgsConstructor
public class PayWechatJsapiPrepayService {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatPayRouter payWechatPayRouter;

    public WechatJsapiPrepayVO prepay(BasicPayOrderData payOrderData) throws Exception {
        if (!payOrderData.isTravelFinanceOrder()) {
            throw new IllegalArgumentException("wechatJsapiPrepay 仅支持杏花村财务主单（须设置 bizScene）");
        }
        PayWechatConfig config = payWechatWxPayClientHolder.findActiveConfig(payOrderData.getTenantId());
        if (config == null || !PayWechatCredentialSupport.isWxEnabled(config)) {
            throw new IllegalStateException("未启用真实微信 V3 下单：请在管理后台【支付 · 微信配置】开启");
        }
        PayWechatPayRouteResult routeResult = payWechatPayRouter.prepay(payOrderData);
        return toVo(routeResult.getJsapiResult());
    }

    public PayWechatPrepayRouteSnapshotDTO previewRoute(BasicPayOrderData payOrderData) {
        return payWechatPayRouter.previewSnapshot(payOrderData);
    }

    private static WechatJsapiPrepayVO toVo(WxPayUnifiedOrderV3Result.JsapiResult jsapi) {
        WechatJsapiPrepayVO vo = new WechatJsapiPrepayVO();
        vo.setMock(false);
        vo.setAppId(jsapi.getAppId());
        vo.setTimeStamp(jsapi.getTimeStamp());
        vo.setNonceStr(jsapi.getNonceStr());
        vo.setPackageValue(jsapi.getPackageValue());
        vo.setSignType(jsapi.getSignType());
        vo.setPaySign(jsapi.getPaySign());
        String pkg = jsapi.getPackageValue();
        if (pkg != null && pkg.startsWith("prepay_id=")) {
            vo.setPrepayId(pkg.substring("prepay_id=".length()));
        }
        return vo;
    }
}
