package apicrypt

import (
	"PaymentCenter/app/constants/errorcode"
	"PaymentCenter/app/models/appmodel"
	"PaymentCenter/app/utils/encrypt/sm4"
	"strconv"
)

func NewSm4(app *appmodel.App) ApiCrypt {
	return &SM4{
		App: app,
	}
}

func (r *SM4) Encrypt(data string) (encryptData []byte, errCode int) {
	if r.App.MerchantPublicKey == "" || r.App.PrivateKey == "" {
		return nil, errorcode.AppSM4DecryptKeyNotFound
	}
	encryptDataString, err := sm4.Sm4Encrypt(strconv.FormatInt(r.App.Id, 10), r.App.PrivateKey, r.App.MerchantPublicKey, data, "", true)
	if err != nil {
		return nil, errorcode.AppSM4EncryptFail
	}
	encryptData = []byte(encryptDataString)
	return
}

func (r *SM4) Decrypt(encryptData string) (decryptData []byte, errCode int) {
	if r.App.PrivateKey == "" || r.App.MerchantPublicKey == "" {
		return nil, errorcode.AppSM4DecryptKeyNotFound
	}

	decryptDataString, err := sm4.Sm4Decrypt(strconv.FormatInt(r.App.Id, 10), r.App.PrivateKey, r.App.MerchantPublicKey, encryptData, true)
	if err != nil {
		return nil, errorcode.AppSM4DecryptFail
	}
	decryptData = []byte(decryptDataString)
	return

}