package com.wzj.soopin.transaction.wechat;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;

@Data
@Configuration
@ConfigurationProperties(prefix = "wechat.pay.v3")
public class WechatPayConfig {

    private String mchId;
    private String mchSerialNo;
    private String apiV3Key;
    private String privateKeyPath;
    private String transferNotifyUrl;
    private String appId;
    private String secret;

    @Bean
    public PrivateKey merchantPrivateKey() throws IOException {
        if (privateKeyPath.startsWith("classpath:")) {
            // 处理类路径资源
            String path = privateKeyPath.substring("classpath:".length());
            Resource resource = new ClassPathResource(path);
            try (InputStream inputStream = resource.getInputStream()) {
                return WXPayUtility.loadPrivateKey(inputStream);
            }
        } else if (privateKeyPath.startsWith("file:")) {
            // 处理文件系统路径
            String filePath = privateKeyPath.substring("file:".length());
            return WXPayUtility.loadPrivateKeyFromPath(filePath);
        } else {
            // 默认按文件系统路径处理
            return WXPayUtility.loadPrivateKeyFromPath(privateKeyPath);
        }
    }
}
