package utils

import (
	"github.com/juju/errors"
	"github.com/tidbcloud/ecosystem-service/config"
	"github.com/tidbcloud/pkgv2/secret/encrypt"
	"github.com/tidbcloud/pkgv2/secret/provider"
)

type Encryptor interface {
	EncryptBase64(text string) (string, error)
	DecryptBase64(encryptedEncoded string) (string, error)
}

type encryptorImpl struct {
	enc encrypt.Encryptor
}

func InitEncryptor(conf *config.ConfigWrapper) Encryptor {
	CMKArn := conf.ServiceConfig.CMKArn
	enc, err := provider.NewSecretEncryptor(CMKArn)
	if err != nil {
		panic("initialize encryptor failed")
	}
	return &encryptorImpl{enc: enc}
}

func (e *encryptorImpl) EncryptBase64(text string) (string, error) {
	secretTxt, err := encrypt.EncryptBase64(e.enc, encrypt.Secret(text))
	if err != nil {
		return "", errors.Annotate(err, "encrypt failed")
	}
	return secretTxt, nil
}

func (e *encryptorImpl) DecryptBase64(encryptedEncoded string) (string, error) {
	plainText, err := encrypt.DecryptBase64(e.enc, encryptedEncoded)
	if err != nil {
		return "", errors.Annotate(err, "decrypt failed")
	}
	return string(plainText), nil
}
