package com.ylx.common.config;

import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceApacheHttpImpl;
import com.ylx.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class WxPayBeanConfig {

    @Autowired
    private WechatPayConfig wxPayConfig;

    @Bean
    public WxPayService wxPayService() {
        // 1. 全局前置必填参数校验（启动即校验，提前暴露问题）
        checkWxPayConfig();

        // 2. 映射SDK原生配置
        WxPayConfig sdkConfig = new WxPayConfig();
        sdkConfig.setAppId(wxPayConfig.getAppId());
        sdkConfig.setMchId(wxPayConfig.getMchId());
        sdkConfig.setApiV3Key(wxPayConfig.getMchKey());
        sdkConfig.setPrivateCertPath(wxPayConfig.getCertPath());
        sdkConfig.setPrivateKeyPath(wxPayConfig.getCertKeyPath());
        sdkConfig.setNotifyUrl(wxPayConfig.getNotifyUrl());

        // 3. V3推荐Apache HTTP实现，替换旧WxPayServiceImpl
        WxPayService payService = new WxPayServiceApacheHttpImpl();
        payService.setConfig(sdkConfig);
        log.info("微信支付V3客户端初始化完成，商户号:{}", wxPayConfig.getMchId());
        return payService;
    }

    /**
     * 启动时校验所有必填支付配置，缺失直接抛异常阻止项目启动
     */
    private void checkWxPayConfig() {
        if (StrUtil.isBlank(wxPayConfig.getAppId())) {
            throw new ServiceException("微信支付配置缺失：wx.app-id不能为空");
        }
        if (StrUtil.isBlank(wxPayConfig.getMchId())) {
            throw new ServiceException("微信支付配置缺失：wx.mch-id不能为空");
        }
        if (StrUtil.isBlank(wxPayConfig.getMchKey())) {
            throw new ServiceException("微信支付配置缺失：wx.mch-key(APIv3密钥)不能为空");
        }
        if (StrUtil.isBlank(wxPayConfig.getCertPath()) || StrUtil.isBlank(wxPayConfig.getCertKeyPath())) {
            throw new ServiceException("微信支付证书配置缺失：cert-path/cert-key-path证书路径不能为空");
        }
        if (StrUtil.isBlank(wxPayConfig.getNotifyUrl())) {
            log.warn("微信支付回调地址notify-url未配置，支付回调无法接收");
        }
    }
}