# app/api/v1/crypto_api.py
from fastapi import APIRouter, HTTPException, Request
from app.schemas.crypto import EncryptRequest, EncryptResponse, DecryptRequest, DecryptResponse
from app.core.config import settings
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
import base64, json, logging
from app.core.crypto import decrypt_data,encrypt_data
# from app.core.crypto_key import key_iv_from_settings

logger = logging.getLogger(__name__)
router = APIRouter(tags=["Crypto"])

# key, iv = key_iv_from_settings()

# Encryption endpoint
@router.post("/encrypt")
async def encrypt(request: Request):
    try:
        # Read the raw JSON body from the request
        raw_data = await request.json()
        
        # Convert the raw data to a JSON string and encrypt it
        plaintext = json.dumps(raw_data)  # Convert to string for encryption
        encrypted_token = encrypt_data(plaintext)
        
        return encrypted_token
    except Exception as e:
        logger.error(f"Encryption failed: {e}")
        raise HTTPException(status_code=500, detail="Encryption failed")

# Decryption endpoint
@router.post("/decrypt")
async def decrypt(request: Request):
    try:
        # Read the raw JSON body from the request
        raw_data = await request.json()
        
        # Get the token from the request data
        plaintext = json.dumps(raw_data)  # Convert to string for encryption
        decrypted_token = decrypt_data(plaintext)

        return decrypted_token
    except Exception as e:
        logger.error(f"Decryption failed: {e}")
        raise HTTPException(status_code=500, detail="Decryption failed")