package helper

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/sha256"
	"encoding/base64"
	"log"

	lzstring "github.com/daku10/go-lz-string"
)

func StringDecrypt(key string, encryptedString string) (string, error) {
	keyHash := sha256.Sum256([]byte(key))
	keyHashBytes := keyHash[:]

	iv := keyHashBytes[:16]

	encryptedBytes, err := base64.StdEncoding.DecodeString(encryptedString)
	if err != nil {
		return "", err
	}

	block, err := aes.NewCipher(keyHashBytes)
	if err != nil {
		return "", err
	}

	mode := cipher.NewCBCDecrypter(block, iv)

	decrypted := make([]byte, len(encryptedBytes))
	mode.CryptBlocks(decrypted, encryptedBytes)

	decrypted = RemovePKCS7Padding(decrypted)

	dataResp, err := lzstring.DecompressFromEncodedURIComponent(string(decrypted))
	if err != nil {
		log.Fatalf("Error decompress: %v", err)
	}
	return dataResp, nil
}

func RemovePKCS7Padding(data []byte) []byte {
	paddingLength := int(data[len(data)-1])
	return data[:len(data)-paddingLength]
}
