package com.sf.payment.utils;
import cn.hutool.core.io.resource.ClassPathResource;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

import java.util.Map;

public class HuaweiTokenGenerator {

    public static String createToken(Map<String, Object> jwtHeader, Map<String, Object> jwtPayload) {
        try {
            // AppGallery Connect 华为应用内支付配置密钥，下载私钥文件
            ClassPathResource classPathResource = new ClassPathResource("IAPKey_0ae3e1be-374b-43a5-a297-045addbf76eb.p8");
            InputStream IAPKeyStream = classPathResource.getStream();
            String content = IOUtils.toString(IAPKeyStream, String.valueOf(StandardCharsets.UTF_8));
            String privateKey = content
                    .replace("-----BEGIN PRIVATE KEY-----", "")
                    .replaceAll("\\R+", "")
                    .replace("-----END PRIVATE KEY-----", "");
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKey);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            ECPrivateKey ecPrivateKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec);
            return JWT.create()
                    .withHeader(jwtHeader)
                    .withPayload(jwtPayload)
                    .sign(Algorithm.ECDSA256(ecPrivateKey));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }
    }
}
