package alipay

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"strings"
)

// 从证书文件中提取公钥
func getPublicKey(certPath string) (string, error) {
	// 读取证书文件内容
	certData, err := ioutil.ReadFile(certPath)
	if err != nil {
		return "", fmt.Errorf("failed to read certificate file: %w", err)
	}

	// 解码 PEM 编码的证书
	block, _ := pem.Decode(certData)
	if block == nil {
		return "", fmt.Errorf("failed to decode PEM block")
	}

	// 解析证书
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		return "", fmt.Errorf("failed to parse certificate: %w", err)
	}

	// 获取公钥
	pubKey := cert.PublicKey

	// 转换公钥为 PEM 格式
	pubKeyBytes, err := x509.MarshalPKIXPublicKey(pubKey)
	if err != nil {
		return "", fmt.Errorf("failed to marshal public key: %w", err)
	}

	// 创建 PEM 块
	pemBlock := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: pubKeyBytes,
	}

	// 编码为 PEM 格式字符串
	pemBytes := pem.EncodeToMemory(pemBlock)
	publicKey := strings.TrimSpace(string(pemBytes))

	return publicKey, nil
}