# 🔐 Node.js Encryption Logic Recap
# In Node.js, they are using:
# aes-256-cbc
# key (32 bytes)
# iv (16 bytes)
# Base64-encoded output

# You need to:

# ✅ Encrypt request payload using AES-256-CBC
# ✅ Send as Base64-encoded string
# ✅ Decrypt API response the same way

# 🐍 Python Equivalent (Django)
# You’ll use Cryptodome.Cipher.AES in Python.

# ✅ Install PyCryptodome (if not done)
# pip install pycryptodome
# ✅ Python Equivalent Functions

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
import json

def encrypt_data(data, key, iv):
    try:
        if isinstance(data, dict):
            data = json.dumps(data)
        data_bytes = data.encode('utf-8')
        key_bytes = key.encode('utf-8')
        iv_bytes = iv.encode('utf-8')

        cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
        encrypted = cipher.encrypt(pad(data_bytes, AES.block_size))
        return base64.b64encode(encrypted).decode('utf-8')
    except Exception as e:
        print("Encryption Error:", e)
        return data


def decrypt_data(encrypted_str, key, iv):
    try:
        encrypted_bytes = base64.b64decode(encrypted_str)
        key_bytes = key.encode('utf-8')
        iv_bytes = iv.encode('utf-8')

        cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
        decrypted = unpad(cipher.decrypt(encrypted_bytes), AES.block_size)
        return decrypted.decode('utf-8')
    except Exception as e:
        print("Decryption Error:", e)
        return encrypted_str


# 🔑 Sample Usage
# Base Url : https://send.bulkgv.net/API/v1
# username : ZVBPNPCHVMBUAQTZYOWPLTXVWXWYERDS
# password : ]soLj$si!x6IL![KP~rkQ^sXG^hT3yJS
# key : 6d66fb7debfd15bf716bb14752b9603b
# iv : 716bb14752b9603b
key = "6d66fb7debfd15bf716bb14752b9603b"
iv = "716bb14752b9603b"

payload = {
    "mobile": "9999999999",
    "amount": 200,
    "voucher_type": "AMAZON"
}

encrypted = encrypt_data(payload, key, iv)
print("Encrypted:", encrypted)

# After API call
decrypted = decrypt_data(encrypted, key, iv)
print("Decrypted:", decrypted)
# Once you confirm:
# Key & IV length is exactly 32 and 16 characters respectively
# API sample request/response JSON
